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