如何跳过会话创建?

时间:2015-08-13 18:29:06

标签: ruby-on-rails ruby session

nil用户点击"注册"我鼓励他在登录前提交目标,习惯和价值。

但他可以点击以下内容跳过其中一种表格:

enter image description here

问题是,如果他现在跳过表单,则会弹出一条错误消息:

TypeError in UsersController#create
no implicit conversion of nil into String

在这个例子中,我跳过习惯表格,以便在@user.habits.create(

上提出

users_controller

  def create
    @user = User.new(user_params)
    if @user.save
      # Goals
      name = session.delete(:goal_name)
      deadline = session.delete(:goal_deadline)
      # Values
      vname = session.delete(:valuation_name)
      vimage = session.delete(:valuation_image)
      # Habits
      date_started = session.delete(:habit_date_started)
      committed = session.delete(:habit_committed)
      trigger = session.delete(:habit_trigger)
      action = session.delete(:habit_action)
      target = session.delete(:habit_target)
      reward = session.delete(:habit_reward)
      missed_days = session.delete(:habit_missed_days)
      # Create
      @user.habits.create(date_started: Date.parse(date_started), committed: committed, trigger: trigger, action: action, target: target, reward: reward, missed_days: missed_days).create_with_current_level
      @user.goals.create(name: name, deadline: deadline)
      @user.valuations.create(name: vname, image: vimage)
      @user.send_activation_email
      redirect_to root_url
    else
      render 'new'
    end
  end

我们如何允许用户跳过?我一直试图包含各种if/else语句,但我很难设置正确的方法来触发条件。

1 个答案:

答案 0 :(得分:1)

我将假设如果他们提交表单,则会填充所有值。那说:

<强> users_controller

  def create
    @user = User.new(user_params)
    make_habit = false
    make_goal = false
    make_valuation = false

    if @user.save
      # Goals
      name = session.delete(:goal_name)
      deadline = session.delete(:goal_deadline)
      make_goal = true  if !name.blank? && !deadline.blank?

      # Values
      vname = session.delete(:valuation_name)
      vimage = session.delete(:valuation_image)
      make_valuation = true  if !vname.blank? && !vimage.blank?

      # Habits
      date_started = session.delete(:habit_date_started)
      committed = session.delete(:habit_committed)
      trigger = session.delete(:habit_trigger)
      action = session.delete(:habit_action)
      target = session.delete(:habit_target)
      reward = session.delete(:habit_reward)
      missed_days = session.delete(:habit_missed_days)
      make_habit = true  if !date_started.blank? && !committed.blank? #(... continue for whatever else you want to make sure is there)

      # Create
      @user.habits.create(date_started: Date.parse(date_started), committed: committed, trigger: trigger, action: action, target: target, reward: reward, missed_days: missed_days).create_with_current_level  if make_habit
      @user.goals.create(name: name, deadline: deadline)  if make_goal
      @user.valuations.create(name: vname, image: vimage)  if make_valuation
      @user.send_activation_email
      redirect_to root_url
    else
      render 'new'
    end
  end