Rails 3.1: Custom validation message on join table of has_many through relationship?

妖精的绣舞 提交于 2019-12-12 01:47:00

问题


I have a Meal model that has_many :foods, :through => :servings. Meal also:

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

The Serving model has a field called serving_amount and a field called amount_recorded. In the Serving model, I currently use this validation:

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

The message returned if the validation fails is terrible. This is compounded by the fact that each meal may have multiple servings.

How do I create a custom validation message that refers to the name of the food for which the serving size is invalid? For example, I would like it to say, "You entered an invalid serving size for Watermelon," if amount_recorded is true for a serving of a Food with name watermelon and the validation fails.


回答1:


I would try the validates_each method. When calling the method, you pass it a block that will be passed the record instance (from the 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

That means you can access any of the records attributes, including the name, and easily construct the error message.



来源:https://stackoverflow.com/questions/8479113/rails-3-1-custom-validation-message-on-join-table-of-has-many-through-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!