rails: accepts_nested_attributes_for breaks the uniqueness with scope validation

Hi All, I think for the following configuration accepts_nested_attributes_for + validation seems to be broken!! Rails 4.2.1 Ruby 2.1.3

class Country < ActiveRecord::Base
  has_many :cities, dependent: :destroy
  accepts_nested_attributes_for :cities
end

class City < ActiveRecord::Base
  belongs_to :country
  validates :language , uniqueness: { scope: :country_id }
end

country = Country.new(description:'abc', language: 'en-US', cities:[City.new(language: 'en-US', text: 'abc'), City.new(language: 'en-US', text: 'abc')])
country.save!

works!!

c1 = City.new(language: 'en-US', text: 'abc', country_id: 1)
c1.save!

c2 = City.new(language: 'en-US', text: 'xyz', country_id: 1)
c2.save! #does not work

Here is executable report https://gist.github.com/spurnaye/0ab33d62dc1f12751ee0 Appreciate efforts on this!

About this issue

  • Original URL
  • State: open
  • Created 11 years ago
  • Reactions: 66
  • Comments: 74 (15 by maintainers)

Commits related to this issue

Most upvoted comments

How is this not fixed yet? Nearly 5 years later…

Bumping in 2020. Any fix?

I’ve found a (really hacky) workaround. I abuse the if proc to assign the foreign key.

  # Hacky workaround for Rails bug #20676
  validates_uniqueness_of :name, scope: [:project, :parent, :test_plan], if: -> (record) {record.test_plan_id = record.test_plan.id if record.test_plan.present?; true}

Now everything works as expected.

Can reproduce on Rails 5 beta 3

Problem still exists with Rails 6 and Ruby 2.6.5. Please fix this.

In my case I’m calling .valid?, and so the associated models are not saved to the database at all. I still think validation should fail though. I think the only way for this to work would be for the validation to check if the scope refers to an association, and if so validate uniqueness against sibling objects models in memory.

For example:

class Parent < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  validates :name, uniqueness: { scope: :parent }
end

# I'd expect this to raise a ValidationError
Parent.new(children_attributes: [{ name: 'John' }, { name: 'John' }]).validate!

In this case I’d imagine that when each Child is validated, the UniquenessValidator would look up parent.children and see if any of the other children share the same name.

Looking at the code forUniquenessValidator at the moment it’s hard-coded to work using where() (see line 95). That’s fine when individual models are being created or updated, but won’t work when you’re creating multiple models at once as we do with accepts nested attributes.

I have the same issue in rails 5.0.0.1.

There is no other solution than setting a unique index on 2 columns and handle the ActiveRecord::RecordNotUnique exception in the controller?

I’ve gone with @catogonzalez 's solution, adapted to be reusable across different classes.

class NestedUniquenessValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if siblings(record).any? { |sibling| sibling.public_send(attribute) == value }
      record.errors.add(attribute, "has already been taken")
    end
  end

  private

  def siblings(record)
    begin
      siblings = record.parent.public_send(sibling_accessor(record))
    rescue NoMethodError
      raise "The record should implement the method `parent`, which returns the associated instance of the class which specifies `accepts_nested_attribute_for [child_class]`"
    end

    siblings - [record]
  end

  # Works out the method for accessing the collection of nested objects (children of the parent class) based on the record's class name
  def sibling_accessor(record)
    # Your implementation here (project-dependent)
  end
end

I am using this alongside ActiveRecord’s validator in the classes in question, since the nested_uniqueness validator doesn’t cover cases where records are created without using accepts_nested_attributes_for:

class SuperClass < ApplicationRecord
  has_many :sub_classes
  accepts_nested_attributes_for :sub_classes
end

class SubClass < ApplicationRecord
  belongs_to :super_class

  validates :detail, uniqueness: {scope: :super_class}, if: -> { detail.present? && errors[:detail].none? }
  validates :detail, nested_uniqueness: true, if: -> { detail.present? && errors[:detail].none? }

  def parent
    super_class
  end
end

My not-so-hacky solution that might as well be converted to a custom validator if you have to use it in many places:

validate :my_attribute_uniqueness

private 

# parent_record: the one declaring the accepts_nested_attributes_for
# nested_collection: the name of the collection as declared in accepts_nested_attributes_for :nested_collection
# my_attribute: the name of the attribute you want to validate with uniqueness: { scope: ... }
# 
def my_attribute_uniqueness
  return if parent_record.nil?
  errors.add(:my_attribute, :taken) if parent_record.nested_collection.any? { |sibling| sibling != self && sibling.my_attribute == self.my_attribute }
end

The same issue persists in rails 4.2.7 as well

Same issue with Rails 5.2.3 on Ruby 2.6.3. Please fix.

Just commenting here to say that I also am facing this issue with rails 5.2.2

Updated reproduction script

The key issue is that the validation of the associated record is called before saving the parent record which leads into not finding the uniqueness validation error . What we could do is to define a set of validations (just uniqueness for now) which should run after the parent record has been saved and if any of such validation exists we should call validate on the associated record also after save/update and rollback the transaction in case of validation error.

I’d like some feedback from the core team about this proposal.

Fix please

Not that I expected anything else, but the problem continues to exist in Rails 6.0 (beta).

I modify @Jaroost 's solution a little bit to work with scope:

def self.validates_uniqueness(*attr_names)
    # Set the default configuration
    configuration = { attribute_name: :name, scope: [], message: 'has already been taken' }

    # Update defaults with any supplied configuration values
    configuration.update(attr_names.extract_options!)

    validates_each(attr_names) do |record, record_attr_name, value|
      duplicates = Set.new
      attr_name = configuration[:attribute_name]
      scope = configuration[:scope]
      value.map do |obj|
        ob = {}
        ob[attr_name] = obj.try(attr_name)
        scope.each { |att| ob[att] = obj.try(att) }
        if duplicates.member?(ob)
          # mark the record as in error so validation will detect a failure
          record.errors.add(record_attr_name, '')
          obj.errors.add(attr_name, configuration[:message])
        else
          duplicates.add(ob)
        end
      end
    end
  end

So that you can do something like this on your model:

validates_uniqueness :teacher_id, scope: [:semester_id, :class_id]

Verified this on Rails 6.0.3.2. Would be great if this is addressed.

I updated @jaroost’s final solution with @thuhuongly’s changes, plus the following:

  1. Elimination of errors on the nested model. If this is necessary, it can be handled in the nested model itself rather than the parent model.
  2. Elimination of a default value for the unique attribute name on the nested model, since this will create hard-to-track-down bugs.
  3. Rails 5 changes (adding errors by key rather than by string).
  4. Tons of variable renaming for clarity.
  5. My own general refactoring to get rid of looped variable re-declaration, etc.

I made the Rails 5 error key configurable; obviously whatever error key you use, either your own or a custom one, needs to be added to i18n either at the base activemodel level or in your specific model:

  • en.errors.messages.<your key>
  • en.activerecord.errors.models.<your_model>.attributes.<your nested attribute>.<your key>
  def self.validate_nested_uniqueness_of(*nested_attrs)
    opts      = nested_attrs.extract_options!
    uniq_attr = opts[:uniq_attr]
    scope     = opts[:scope    ] || []
    error_key = opts[:error_key] || :nested_taken
    message   = opts[:message  ] || nil

    raise ArgumentError unless uniq_attr.present?

    validates_each(nested_attrs) do |record, nested_attr, nested_values|
      dupes = Set.new

      nested_values.reject(&:marked_for_destruction?).map do |nested_val|
        dupe            = scope.each.inject({}) { |memo, (k)| memo[k] = nested_val.try(k); memo }
        dupe[uniq_attr] = nested_val.try(uniq_attr)

        if dupes.member?(dupe)
          record.errors.add(nested_attr, error_key, message: message)
        else
          dupes.add(dupe)
        end
      end
    end
  end

Usage is like this:

  # parent model Work

  has_many :credits,       inverse_of: :work, dependent: :destroy
  has_many :contributions, inverse_of: :work, dependent: :destroy

  accepts_nested_attributes_for :credits, allow_destroy: true,
    reject_if: proc { |attrs| attrs["creator_id"].blank? }

  accepts_nested_attributes_for :contributions, allow_destroy: true,
    reject_if: proc { |attrs| attrs["creator_id"].blank? }

  validate_nested_uniqueness_of :credits,       uniq_attr: :creator_id
  validate_nested_uniqueness_of :contributions, uniq_attr: :creator_id, scope: [:role_id]
  # child model Credit

  validates :creator_id, uniqueness: { scope: [:work_id] }
  # child model Contribution

  validates :creator_id, uniqueness: { scope: [:work_id, :role_id] }
  # activemodel.en.yml

  en:
    errors:
      messages:
        nested_taken: "Please choose unique values."

Agreed, there still doesn’t seem to be a fix for it. I have a model with a nested form and then I’m also trying to add validations for presence and other data quality in the model thats being nested, but to no avail.

In my use case I could do something along the lines of throwing some errors in the controller for validation, but its a little sloppy. Could potentially just lax up on validations.

@rafaelfranca do you have any particular thoughts on the best way to address this? I could contribute a PR given a bit of direction.

I am using Rails 6, and updated @armchairdj solution with case sensitivity

def self.validate_nested_uniqueness_of(*nested_attrs)
  opts           = nested_attrs.extract_options!
  watch          = opts[:watch]
  case_sensitive = opts[:case_sensitive]
  scope          = opts[:scope    ] || []
  error_key      = opts[:error_key] || :nested_taken
  message        = opts[:message  ] || nil

  raise ArgumentError unless watch.present?
  validates_each(nested_attrs) do |record, nested_attr, nested_values|
    dupes = Set.new
    nested_values.reject(&:marked_for_destruction?).map do |nested_val|
      dupe        = scope.each.inject({}) { |memo, (k)| memo[k] = nested_val.try(k); memo }
      dupe[watch] = nested_val.try(watch)
      dupe[watch] = dupe[watch].try(:downcase)  if case_sensitive == false

      if dupes.member?(dupe)
        record.errors.add(:base, error_key, message: message)
      else
        dupes.add(dupe)
      end
    end
  end
end

# parent model
validate_nested_uniqueness_of :fields, watch: :name, scope: [:template_id], case_sensitive: false

Not fixed 👍

Please fix asap.

Please fix this

Hi @djezzzl it’s a great gem, and it works in some cases, but just FYI not for polymorphic belongs_to (obviously since there is no FK). We still need a general solution there.

Still happening on Rails 5.2.1; Most workarounds in this topic is pretty hacky. I might as well drop accept accepts_nested_attributes_for all together and create the parent and child separately.

@thuhuongly This doesn’t seem to work on rails 5.1.5. The “value.map” throws an exception as it’s expecting an array but a string is encountered.

I having this issue on rails 4.2.3

I’ve ended up with this gem https://github.com/toptal/database_validations#rescue-option

class Approver < ApplicationRecord
  belongs_to :approvable, polymorphic: true
  belongs_to :user 
  validates_db_uniqueness_of :user_id, scope: %i[approvable_id approvable_type], rescue: :always
end

class Template < ApplicationRecord
  has_many :approvers, -> { order(position: :asc) }, as: :approvable
  accepts_nested_attributes_for :approvers, reject_if: :all_blank, allow_destroy: true
end

Works fine with create / update template record

@spurnaye This is how I worked around it:

class Country < ActiveRecord::Base
  has_many :cities, dependent: :destroy
  accepts_nested_attributes_for :cities
end

class City < ActiveRecord::Base
  belongs_to :country
  validates :language , uniqueness: { scope: :country_id }

  #
  # This after save callback will make sure that the transaction initiated by accepts_nested_attributes_for aborted
  # if the children are saved in spite of having validation errors.
  #
  after_save :raise_if_saved_with_errors
  def raise_if_saved_with_errors
    raise ActiveRecord::RecordInvalid.new(self) if errors.any?
  end
end

I wouldn’t count on your workaround being temporary. This issue has been open for four years and two major releases. I’m not sure if this will ever be fixed.

hello everyone, i decided to implement a simple after_validation on the nested model.

Something like in restricted_endpoint model

validates :code, presence: true, uniqueness: { scope: :client } before_save :restricted_code_should_be_uniq, on: :create

private def restricted_code_should_be_uniq unless client.restricted_endpoints.where(code: code).blank? self.errors.add(:code, :invalid) raise ActiveRecord::RecordInvalid.new(self) end end

this is only temporary until the problem is solved

I am also facing this bug within Rails 5.1.5. Within this stackoverflow post I try to explain my problem and provide a simple solution using a unique database index and a around_save callback.

I still have this problem in Rails 5.0.5, here is a post i made in StackOverflow describing with details.

Confirming presence of issue in Rails 5.0.1 as well

I also have the same issue on rails 5.0.0.1.

Here’s my sample code: class PeopleGroupItem < ApplicationRecord belongs_to :people_group validates :type, presence: true, uniqueness: {scope: :people_group, message: 'combination already used'} validates :value, presence: true end

I also tried scope: :group_id but to no avail.

However, the validation of the presence requirement does work. It’s just the uniqueness check which is ignored.

Can reproduce on master – the only error I’m seeing is with the last test, where the new Country is being created. Would you be willing to do a little bit of some sourcediving and try and figure out where this bug is introduced, and how it can be solved?

I having this issue on rails 4.2.5…

TL;DR Child uniqueness validation should be done only after parent INSERTed.

I have similar issue, and I found that validations with scope are done before the parent record is saved, and it checks for NULL value, instead of real id value that will be saved only after INSERT is completed.