2

Say we've got the following models:

class User < ActiveRecord::Base
    has_many :widgets
    accepts_nested_attributes_for :widgets, allow_destroy: true
end

class Widget < ActiveRecord::Base
    belongs_to :user
    validates :title, presence: true, uniqueness: { scope: [:user_id] }
end

When I save a user with nested widget attributes that contain a duplicate title I get a validation error as expected. What's a good way to avoid the validation error and silently eliminate the duplicate entries before saving?

Thanks.

scttnlsn
  • 2,976
  • 1
  • 33
  • 39

1 Answers1

0

You could just reject the nested attributes if they don't match certain criteria:

accepts_nested_attributes_for :widgets,
  allow_destroy: true,
  reject_if: lambda { |w| Widget.pluck(:title).include?(w.title) && Widget.pluck(:user_id).include?(w.user_id) }
jvperrin
  • 3,368
  • 1
  • 23
  • 33
  • This does not consider duplicate attributes in memory though. For example: `user.widgets_attributes = { '0' => { title: 'Foo' }, '1' => { title: 'Foo' }}` would still attempt to save the duplicate. – scttnlsn Oct 29 '13 at 13:27