Rails 3: Uniqueness validation for nested fields_for

后端 未结 3 1420
不知归路
不知归路 2020-12-29 11:46

A have two models, \"shop\" and \"product\", linked via has_many :through.

In the shop form there are nested attributes for multiple products, and I\'m having a litt

相关标签:
3条回答
  • 2020-12-29 12:21

    To expand on Alberto's solution, the following custom validator accepts a field (attribute) to validate, and adds errors to the nested resources.

    # config/initializers/nested_attributes_uniqueness_validator.rb
    class NestedAttributesUniquenessValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        unless value.map(&options[:field]).uniq.size == value.size
          record.errors[attribute] << "must be unique"
          duplicates = value - Hash[value.map{|obj| [obj[options[:field]], obj]}].values
          duplicates.each { |obj| obj.errors[options[:field]] << "has already been taken" }
        end
      end
    end
    
    # app/models/shop.rb
    class Shop < ActiveRecord::Base
      validates :products, :nested_attributes_uniqueness => {:field => :name}
    end
    
    0 讨论(0)
  • 2020-12-29 12:27

    You could write a custom validator like

    # app/validators/products_name_uniqueness_validator.rb
    class ProductsNameUniquenessValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        record.errors[attribute] << "Products names must be unique" unless value.map(&:name).uniq.size == value.size
      end
    end
    
    # app/models/shop.rb
    class Shop < ActiveRecord::Base
      validates :products, :products_name_uniqueness => true
    end
    
    0 讨论(0)
  • 2020-12-29 12:41

    I found the answer over here :

    https://rails.lighthouseapp.com/projects/8994/tickets/2160-nested_attributes-validates_uniqueness_of-fails

    0 讨论(0)
提交回复
热议问题