session is used when moving to the transition destination while holding data in "wizard format" etc.
A session is a mechanism for temporarily storing information. In Rails, a session stores data in an object called session in the form of a hash.
For example, suppose a site where the page changes when you register as a member. In this case, it is necessary to temporarily store the information entered using the session in the session, move to the next page, and expand it there.
As a premise, it is assumed that member information is saved while transitioning pages using devise.
ruby 2.6.5 rails 6.0.0 devise 4.7.3
Let's implement it!
registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
def new
@user = User.new
end
def create
@user = User.new(sign_up_params)
unless @user.valid?
render :new and return
end
session["devise.regist_data"] = {user: @user.attributes}
@address = @user.build_address
render "new_address"
end
I have written various other things, but I will pay attention to session.
session["devise.regist_data"] = {user: @user.attributes}
{user: @ user.attributes} uses the attributes method to format the data when you want session to hold information in the form of a hash object.
In other words, the attributed @user data is in the session in a hashed state. Now, the input information is assigned to session ["devise.regist_data"] and it is in the retained state.
Next, the page is transitioned and expanded while retaining the data.
registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
#abridgement
def create_address
@user = User.new(session["devise.regist_data"]["user"])
@address = Address.new(useraddress_params)
if @address.valid?
@user.build_address(@address.attributes)
@user.save
session["devise.regist_data"]["user"].clear
sign_in(:user, @user)
else
render "new_address"
end
end
This is also described in various ways, but pay attention to @user at the top.
@user = User.new(session["devise.regist_data"]["user"])
Describes session ["devise.regist_data"] ["user"]. If you have data with {user: 〇〇}, you need to use ["user"]. Also, since session contains information in an array, you can also have information as follows. session["devise.regist_data"] = {user: @user.attributes, address: @user.address}
With this, session can be expanded on the transition destination page and assigned to @user.
After that, you can save using the data assigned to @user.
This time, I introduced how to use session when using devise in "wizard format".
I am a beginner in programming, but I am posting an article in the hope that it will help people who are similarly troubled. See you next time ~
Recommended Posts