Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Nested attributes double records #314

Closed
moneybird opened this Issue Mar 13, 2012 · 0 comments

Comments

Projects
None yet
2 participants
@ghost

ghost commented Mar 13, 2012

I'm experiencing problems with assigning attributes for associated records, after creating the instance the records are added twice to the instance:

FactoryGirl.define do
    factory :invoice do
        company_name      "Test Contact B.V."
        details_attributes {[Factory.attributes_for(:invoice_detail), Factory.attributes_for(:invoice_detail)] }
    end
end
invoice = Factory.build(:invoice, :details_attributes => [Factory.attributes_for(:invoice_detail)])
invoice.details.size # Returns 2

I've tried adding an alias as mentioned in #282, but both aliases don't seem to have any impact.

FactoryGirl.aliases << [/details_attributes/, 'details']
FactoryGirl.aliases << [/(.+)_attributes/, '\1']

It is common behavior for ActiveRecord to add new records to the association when using details_attributes={}. I've debugged FactoryGirl and found out that FactoryGirl::AttributeAssigner.attributes_to_set_on_instance returns the details_attributes attribute twice. So for the invoice factory, the array is:

[:company_name, :details_attributes, :details_attributes]

This causes FactoryGirl to assigned details_attributes twice to the newly created Invoice instance, causing the Detail instances to be added twice to the Invoice.

I'm not really familiar with the alias and ignore strategy implemented in FactoryGirl, but I think it should not be possible to assign an attribute twice to a model. Maybe the attributes_to_set_on_instance array should have unique elements?

I'd love to fix the problem and provide some specs, but I'm in doubt if I'm fully overseeing the problem. Looking forward for a response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment