如何在会话中存储nil用户的目标?

时间:2015-08-09 17:26:15

标签: ruby-on-rails ruby session model-view-controller

如何在会话中保存用户的目标?然后,一旦他注册,保存该目标并将其从会话中删除?

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

enter image description here

目标/ _form.html.erb

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

点击提交后,nil用户的目标应该添加到他的会话中,然后他应该被重定向到注册页面,然后注册他的目标应该添加到他新创建的帐户。< / p>

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]

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

1 个答案:

答案 0 :(得分:2)

目标控制器

userId

用户控制器

  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