I've got the following (sanitized) models:
class Person < ActiveRecord::Base
attr_accessible :name, :first_name, :last_name, :age, :job_title, :salary, :ssn, :prison_convictions, :addresses_attributes
has_many :addresses, inverse_of: :person
accepts_nested_attributes_for :addresses, allow_destroy: true
end
class Address < ActiveRecord::Base
attr_accessible :zip_code, :street,:house_number,
:unique_per_person_government_id
belongs_to :person, inverse_of: :addresses
validates_uniqueness_of :unique_per_person_government_id, scope: :person_id
end
The problem is as follows,
Lets say Person Joe Shmoe has two addresses currently attached to himself
666 Foo Street, 12345 with unique id: “ABCDEFG” and 777 Lucky Avenue, 54321 with unique id: “GFEDCBA”
And lets say that the following post comes through from a form:
{:addresses_attributes =>
{ [0] => {:unique_per_person_government_id => “ABCDEFG”, :street=> “Foo Street”, :house_number => 666, :zip_code=>12345, _destroy => 1}
[1] => {:unique_per_person_government_id => “ABCDEFG”, :street=>”Bar Street”, :house_number => 888, :zip_code => 12345, _destroy => 0}
}
The behavior appears to be that the second (ie the new) record is validated for uniqueness first, failing validation.
The behavior I would like is to quite simply remove all elements that are marked_for_destruction?
before conducting any further validation.
How can I rewire the lifecycle in this way? Is there a better way to achieve this?
Thanks!