如何保存用户在 session 中的目标?然后,一旦他注册,保存该目标并将其从 session 中删除?
在主页上它看起来像这样:
目标/_form.html.erb
<%= simple_form_for(@goal) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :deadline %>
<%= f.submit %>
<% end %>
单击提交后,nil
用户的目标应添加到他的 session 中,然后应将他重定向到注册页面,在该页面上注册时,应将他的目标添加到他新创建的帐户中。
goals_controller
def create
@goal = params[:user] ? current_user.goals.build(goal_params) : Goal.new(goal_params)
if params[:session][:name][:deadline]
session[:name][:deadline] = params[:session][:name][:deadline]
redirect_to signup_url
elsif
@goal.save
track_activity @goal
redirect_to @goal, notice: 'Goal was successfully created'
else
flash.now[:danger] = 'Required Field: "Enter Goal"'
render 'new'
end
end
现在,如果我以 nil
用户身份单击“提交”,我会得到:
NoMethodError in GoalsController#create
undefined method `[]' for nil:NilClass
for line: if params[:session][:name][:deadline]
一旦他注册了,存储在他的 session 中的目标就应该添加到他的帐户中。如果最后一个条件太复杂,我可以将其作为一个单独的问题。
最佳答案
目标 Controller
def create
unless params[:user].present?
# If there is no user, store the goal values to the session
session[:goal_name] = goal_params[:name]
session[:goal_deadline] = goal_params[:deadline]
redirect_to signup_url
else
@goal = current_user.goals.build(goal_params)
if @goal.save
track_activity @goal
redirect_to @goal, notice: 'Goal was successfully created'
else
flash.now[:danger] = 'Required Field: "Enter Goal"'
render 'new'
end
end
用户 Controller
def create
# create user logic
if @user.save
# Grab the session variable at the same time deleting it
gName = session.delete(:goal_name)
gDeadline = session.delete(:goal_deadline)
# You can make this more complex for error handling
@user.goals.create(name: gName, deadline: gDeadline)
redirect_to success_creation_path
else
...
end
end
关于ruby-on-rails - 如何在 session 中存储零用户的目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906887/