HABTM Duplication

I’m experiencing an issue with duplicate entries being added when using has_and_belongs_to_many in my models. I’ve setup the following test Rails project (v3.0.7) here:


The test case which is failing is:

Here’s where I think the issue may reside:

I noticed there were threads in the past with a HABTM duplication error, so I’m not sure if this is a regression of if I’m doing something wrong. Any ideas? Please let me know if I should provide any additional information, thanks!

is it because your fixture files define two members that are active
(so they get added to the invoice too) ?


Hey Fred,

Nice catch, I went ahead and updated my fixtures file (so that no active members are created). However I’m still running into the same issue :frowning:


So what are the members this newly created invoice has?


Hey Fred,

When attempting to save the members with this newly created invice the HABTM relation was trying to add the same member (member_id=1 in my case) twice. However I setup a unique index on the composite key (member_id, invoice_id) so I end up with a SQLite3 ConstraintError being thrown (which I expected).

On another note I just changed my code to include a Participation model that I’m using to support the many-to-many relationship between Member and Invoice. Using has_many :members, :through => :participations works without trying to create duplicate Member entries. So I’m not sure if this is an issue with HABTM or my code. Related changes can be found here:


So everything is working as expected now, just a little bit differently than I would’ve hoped. Thanks for the tips!