本文介绍了如何在会话中存储零用户的目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

goals/_form.html.erb

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

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

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

现在,如果我单击以nil用户身份提交,就会得到:

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.

推荐答案

目标控制器

  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

这篇关于如何在会话中存储零用户的目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:57