默认每次save我们的Model时都会执行validation,但有时候我们希望有一定的条件触发时才执行validation:
[code]
# models/user.rb
validates_presence_of :password, :if => :should_validate_password?
validates_presence_of :country, : on => :create
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
[/code]
[code]
# models/user.rb
validates_presence_of :password, :if => :should_validate_password?
validates_presence_of :country, : on => :create
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
[/code]
本文介绍如何在Rails应用中实现基于特定条件的模型验证。通过示例代码展示了如何使用`:if` 和 `:on`选项来控制何时进行字段验证,如密码和国家字段等。
137

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



