Rails validate_association与模型的错误消息
我使用模型中的validates_associated来使用其他模型的validation代码。 这个问题是validation失败的消息是“..无效”。
我想将模型validation失败的实际描述性错误冒出来!
我发现了这个问题: 与模型的错误消息相关的validation
这看起来像一个非常接近的解决方案:
module ActiveRecord module Validations class AssociatedBubblingValidator value)) end end end end end module ClassMethods def validates_associated_bubbling(*attr_names) validates_with AssociatedBubblingValidator, _merge_attributes(attr_names) end end end end
但实际上它遇到了一个错误:
undefined method `valid?' for #
任何人都可以帮助完成这个几乎工作的工作!?
完整的错误跟踪是:
undefined method `valid?' for # Extracted source (around line #6): 4 5 6 7 8 9 def validate_each(record, attribute, value) (value.is_a?(Array) ? value : [value]).each do |v| unless v.valid? v.errors.full_messages.each do |msg| record.errors.add(attribute, msg, options.merge(:value => value)) end Rails.root: /Users/andyarmstrong/Documents/Personal/clazzoo_main Application Trace | Framework Trace | Full Trace config/initializers/associated_bubbling_validator.rb:6:in `block in validate_each' config/initializers/associated_bubbling_validator.rb:5:in `each' config/initializers/associated_bubbling_validator.rb:5:in `validate_each' app/controllers/events_controller.rb:158:in `block in create'
value
实际上不是一个Array
,而是一个ActiveRecord::Associations::CollectionProxy
。
所以…
value.is_a?(Array) ? value : [value]
value.is_a?(Array) ? value : [value]
#=> [value]
和
[value].each do |v| unless v.valid? # ...... end end
会引起这个错误
undefined method `valid?' for #
你可以试试这个:
module ActiveRecord module Validations class AssociatedBubblingValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) ((value.kind_of?(Enumerable) || value.kind_of?(ActiveRecord::Relation)) ? value : [value]).each do |v| unless v.valid? v.errors.full_messages.each do |msg| record.errors.add(attribute, msg, options.merge(:value => value)) end end end end end module ClassMethods def validates_associated_bubbling(*attr_names) validates_with AssociatedBubblingValidator, _merge_attributes(attr_names) end end end end