ruby-on-rails – 如何在会话中存储nil用户的目标?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何在会话中存储nil用户的目标?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在会话中保存用户的目标?然后,一旦他注册,保存该目标并从会话中删除它?

在主页上它看起来像这样:

目标/ _form.html.erb

<%= simple_form_for(@goal) do |f| %>
  <%= f.text_field :name %>
  <%= f.text_field :deadline %>
  <%= f.submit %>
<% end %>

单击提交后,应将nil用户的目标添加到他的会话中,然后将其重定向注册页面,然后将其注册目标添加到他新创建的帐户中.

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

现在如果我点击提交作为零用户我得到:

NoMethodError in GoalsController#create
undefined method `[]' for nil:NilClass
for line: if params[:session][:name][:deadline]

然后,一旦他注册了存储在他的会话中的目标应该被添加到他的帐户.如果这最后一个条件过于复杂,我可以将它作为一个单独的问题.

解决方法

目标控制器
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

用户控制器

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
原文链接:https://www.f2er.com/ruby/274088.html

猜你在找的Ruby相关文章