我有一个表单向导,可根据对象当前步骤验证某些字段。我遇到的问题是,由于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对象移出模型并进入会话,但我希望尽可能将其附加到模型中并清理。
答案 0 :(得分: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