【发布时间】:2015-08-20 16:19:32
【问题描述】:
我想检查:create 和:update 上的实体属性是否介于0 和5 之间。所以我在我的模型中添加了这样的验证:
class MyObject < ActiveRecord::Base
attr_accessible :first_attribute, :second_attribute
validate :check_attributes, on: :create and :update
private
def check_attributes
if self.first_attribute < 0 || self.first_attribute> 5
errors.add(:first_attribute, "first_attribute must be between 0 and 5")
end
if self.second_attribute < 0 || self.second_attribute > 5
errors.add(:second_attribute , "second_attribute must be between 0 and 5")
end
end
end
它适用于创建:当我尝试创建像 MyObject.create!(first_attribute: 7, second_attribute: 4) 这样的实体时,我收到一个错误。如果我输入一个介于 0 和 5 之间的值,它会创建实体。
但是当我更新像my_entity.update_attributes!(first_attribute: 7) 这样的现有实体时,它允许更新,因为它没有进入验证函数。
如何使它适用于两种方法(创建和更新)?
【问题讨论】:
标签: ruby-on-rails ruby validation model callback