How to store nil user's goal in a session?

2019-01-27 01:24发布

How to save a user's goal in his session? Then once he signed up, save that goal and delete it from the session?

On the home page it looks like this:

enter image description here

goals/_form.html.erb

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

Upon clicking submit, the nil user's goal should be added to his session and then he should be redirected to the signup page whereupon signing up his goal should be added to his newly created account.

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

Right now if I click submit as a nil user I get:

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

Then once he signed up the goal stored in his session should be added to his account. If this last condition is too complex I can make it a separate question.

1条回答
冷血范
2楼-- · 2019-01-27 02:00

Goals 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

User 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
查看更多
登录 后发表回答