Low commit activity in last 3 years
A long-lived project that still receives updates
Validate uniqueness of multiple newly associated records
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

>= 7.0.0, < 7.3.0
 Project Readme

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