By default, validations will take place every time the model is saved. Sometimes you only want a validation to happen when certain conditions are met. See how to do that in this episode.
# models/user.rb
validates_presence_of :password, :if => :should_validate_password?
validates_presence_of :country
validates_presence_of :state, :if => :in_us?
attr_accessor :updating_password
def in_us?
country == 'US'
end
def should_validate_password?
updating_password || new_record?
end
# in controller
@user.updating_password = true
@user.save
# or...
@user.save(false)
本文介绍了一种在Ruby on Rails中实现条件验证的方法。通过定义特定条件下的验证规则,可以在保存模型时选择性地进行验证。示例代码展示了如何根据是否更新密码来决定是否验证密码字段的存在。
261

被折叠的 条评论
为什么被折叠?



