Skip to content

Instantly share code, notes, and snippets.

@avescodes
Created June 16, 2009 14:14
Show Gist options
  • Save avescodes/130698 to your computer and use it in GitHub Desktop.
Save avescodes/130698 to your computer and use it in GitHub Desktop.
# So Tags has many "Freetaggables", a polymorphic association. Contacts is one of those freetaggables.
# My mentor was working on some old imports and this bug crops up.
# The code below raises an error. The record is invalid for some reason.
# Turns out since the join has a composite key it is failing - it isn't unique. That doesn't seem possible.
# It just so happens there is a really subtle bug where if you don't save both models before associating them you get a duplicate record in the join
it "should not create duplicate taggings" do
t = Tag.create(:title => 'auto tag')
c = Contact.new
c.tags << t
lambda { c.save }.should_not raise_error
#EHH, wrong. Raises error "#<ActiveRecord::RecordInvalid: Validation failed: Freetaggable type has already been taken>"
# Sooooo descriptive
end
# Add the appropriate save and we no longer have a problem
it "should not create duplicate taggings" do
t = Tag.create(:title => 'auto tag') # create implies a save here
c = Contact.new
c.save
c.tags << t
lambda { c.save }.should_not raise_error
end
# I only found this out from a rails lighthouse ticket
# https://rails.lighthouseapp.com/projects/8994/tickets/177-regression-of-ticket-2888-habtm-inserts-duplicate-rows-into-join-table
# that implied to me the expect action of the developer is too save both models beforehand. Doing so works - it would be nice, however, if the association adding (#<<) would let me know I hadn't saved though.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment