Create a form in a wizard format when registering and profile. I wanted to save the image in my profile, but it didn't work, so I wrote it as a memorandum.
What is the wizard format? For those who say Please refer to here
MacOS Catalina 10.15.6 Rails 6.0.0 Ruby 2.6.5
I'm trying to register as a user using devise. Only nickname is added to the user table. The profile table includes a twitter link. I want to save an image with active_strage in the profile table.
Regarding the implementation of these functions This article is quite close, so I referred to it.
In the wizard format, I was able to save everything except the image, but the image is not saved.
registrations_controller
class Users::RegistrationsController < Devise::RegistrationsController
def create
@user = User.new(sign_up_params)
unless @user.valid?
render :new and return
end
session["devise.regist_data"] = {user: @user.attributes}
session["devise.regist_data"][:user]["password"] = params[:user][:password]
@profile = @user.build_profile
render :new_profile
end
def create_profile
@user = User.new(session["devise.regist_data"]["user"])
@profile = Profile.new(profile_params)
unless @profile.valid?
render :new_profile
end
@user.build_profile(@profile.attributes)
@user.save
session["devise.regist_data"]["user"].clear
sign_in(:user, @user)
redirect_to root_path
end
private
def profile_params
params.require(:profile).permit(:avatar, :favorite_beer, :twitter_link, :info)
end
It seems that the following description in this was bad.
registrations_controller
@user.build_profile(@profile.attributes)
@user.save
Here, @user and @profile are associated with build and saved together with @ user.save, but it seems that it is not working well due to saving here. Find this article
Cause The timing when the file is actually saved in Active Storage is when the model is saved and the process is committed, so even if you attach an image from the model before it is saved, the file seems to be in an incomplete state.
It seems that Active Strage can not go unless you save the model properly, so I solved it by changing the description as follows.
registrations_controller
#Saved in each model
# @user.build_profile(@profile.attributes)
@user.save
@profile.user_id = @user.id
@profile.save
Honestly, the cause of the error may be that I used it even though I didn't understand how to save using build. I hope you find it helpful.
Recommended Posts