加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:46:47 所属栏目:百科 来源:网络整理
导读:如何在会话中保存用户的目标?然后,一旦他注册,保存该目标并从会话中删除它? 在主页上它看起来像这样: 目标/ _form.html.erb %= simple_form_for(@goal) do |f| % %= f.text_field :name % %= f.text_field :deadline % %= f.submit %% end % 单击提交后,
如何在会话中保存用户的目标?然后,一旦他注册,保存该目标并从会话中删除它?

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

目标/ _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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读