Search code examples
ruby-on-railsactiverecordmodelrails-activerecord

How to limit uniqueness scope to parent while creating nested attributes?


Example -

class Group < ApplicationRecord
 has_many :options
 accepts_nested_attributes_for :options
end

class Option < ApplicationRecord
 belongs_to :group
 validates :name, uniqueness: { scope: :group_id }
end

If I try to create a new group, I don't want to create duplicate options with same name for the same group. Other groups may have options with same name.

Group.create({
age: 10,
option_attributes: [
{name: "Red"},
{name: "Red"},
],

Is there a way to do this in Rails ?

I don't want to raise duplication errors, I want to create unique option silently.


Solution

  • No, the validation check for the standard methods will create duplication errors. You would need to write your own option_attributes= method so you can check that yourself.