0

我有一个Meal型号has_many :foods, :through => :servingsMeal也:Rails 3.1:通过关系在has_many的连接表上定制验证消息?

accepts_nested_attributes_for :servings, :allow_destroy => true 
validates_associated :servings 

Serving模型有一个名为serving_amount场和场名为amount_recorded。在Serving模式,我现在用这个验证:

validates :serving_size, :numericality => {:greater_than => 0}, :if => :amount_recorded? 

的消息,如果验证失败是可怕的返回。这是因为每餐可能有多份。

如何创建一个自定义验证消息来引用食品大小无效的食品名称?例如,如果amount_recorded对于Foodname西瓜的服务为true并且验证失败,那么我希望它说:“您输入的西瓜无效份量”。

回答

3

我会尝试validates_each方法。当调用该方法,你通过它要传递的记录实例(从docs)块:

validates_each :first_name, :last_name do |record, attr, value| 
    record.errors.add attr, 'starts with z.' if value.to_s[0] == zz 
end 

这意味着你可以访问任何的记录属性,包括名称,方便地构建错误信息。