ActiveRecord: Validate uniqueness of multiple newly associated records,
helpful for mass-assignment with accepts_nested_attributes_for
.
Problem
class Membership
validate :name, uniqueness: {scope: :user_id}
end
user.memberships.build name: 'foo' # thinks it is valid
user.memberships.build name: 'foo' # thinks it is valid
user.save # -> Sql error
Solution
require 'validates_uniqueness_via_association'
class Membership < ActiveRecord::Base
extend ValidatesUniquenessViaAssociation
validates_uniqueness_via_association :name, :user, associated: :memberships
end
user.memberships.build name: 'foo'
user.memberships.build name: 'foo'
user.save # false ... both memberships are marked invalid
Install
gem install validates_uniqueness_via_association
Author
Michael Grosser
michael@grosser.it
License: MIT