【问题标题】:Rails validations for form wizard, best way to update step表单向导的 Rails 验证,更新步骤的最佳方法
【发布时间】:2014-06-16 14:19:02
【问题描述】:

我有一个表单向导,可以根据当前步骤的对象来验证某些字段。我遇到的问题是,由于 current_step 是模型的一部分,我无法在验证失败的情况下更新 current_step。让我告诉你我的意思。

型号

class Goal< ActiveRecord::Base
  validates_presence_of :school_id, if: 'current_step == "school"'
  validates_presence_of :class_id, if: 'current_step == "class"'

控制器

def update
    ...
    if @user.update(params)
#this evaluates to true since the current_step == "school", and school_id is present  
      @user.update(current_step: @user.next_step)
#I am unable to update the current_step, because current_step == "class" now, and the class_id is missing
      redirect_to registration_path(@user)
    else
      render "show"
    end
  end
end

所以基本上,在不触发验证的情况下更新对象的 current_step 的最佳方法是什么?还是有更好的方法来做到这一点?我有一种感觉,我需要将 current_step 对象移出模型并进入会话,但如果可能的话,我想保持它与模型的连接并保持干净。

【问题讨论】:

标签: ruby-on-rails ruby forms validation


【解决方案1】:

你可以做一些简单的事情:

@user.update_attribute(:current_step, @user.next_step)

这不会触发验证。或者你可以像这样将它推入 params 哈希中:

params[:user][:current_step] = @user.next_step

然后做更新:

@user.update(params)

这样你将限制自己使用 1 个 mysql 查询

如果您想查看它,另一种方法是将 current_step 存储在会话中。

上面有一个很好的轨道: http://railscasts.com/episodes/217-multistep-forms

【讨论】:

  • 工作得很好,谢谢,没有意识到有 update_attribute(单数)
猜你喜欢
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 2012-07-27
  • 2019-04-18
  • 1970-01-01
相关资源
最近更新 更多