问题
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