Rails validates_association与模型的错误消息

时间:2015-08-10 09:22:26

标签: ruby-on-rails ruby validation ruby-on-rails-4 associations

我正在使用模型中的validates_associated来使用其他模型的验证代码。这个问题是验证失败的消息是“..无效”。

我想将模型验证失败的实际描述性错误冒泡到顶部!

我发现了这个问题: validates associated with model's error message

这看起来是一个非常接近的解决方案:

module ActiveRecord
  module Validations
    class AssociatedBubblingValidator < ActiveModel::EachValidator
      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
          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 #<TicketType::ActiveRecord_Associations_CollectionProxy:0x007ff86474a478>

任何人都可以帮助完成这项几乎可以完成的工作!?

完整的错误跟踪是:

undefined method `valid?' for #<TicketType::ActiveRecord_Associations_CollectionProxy:0x007ff8646ba148>

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'

1 个答案:

答案 0 :(得分:7)

value实际上不是Array,而是ActiveRecord::Associations::CollectionProxy

因此...

value.is_a?(Array) ? value : [value]#=&gt; [数值]

[value].each do |v|
  unless v.valid?
    # ......
  end
end

会引发错误

undefined method `valid?' for #<TicketType::ActiveRecord_Associations_CollectionProxy:0x007ff86474a478>

你可以试试这个:

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