Skip to content

Instantly share code, notes, and snippets.

@phoward8020
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phoward8020/ffa5fc1b6b3a609c98a1 to your computer and use it in GitHub Desktop.
Save phoward8020/ffa5fc1b6b3a609c98a1 to your computer and use it in GitHub Desktop.
Creating new records with polymorphic associations

Creating new records with polymorphic associations

Step One - Begin with the end in mind:

checkins.create({note:"This is another test"})

Our ultimate goal is to create a checkin record, so start there.

Step Two: Create link to the polymorphable model:

Location.first.checkins.create({note: "This is another test"})

Chain the code from Step One to an existing instance of one of the available polymorphable models (either Event or Location, in this case).

Step Three: The tricky part (aka, "WTF does '<<' mean??")

user.checkins << Location.first.checkins.create({note: "This is another test"})

Per section 4.3.1 of the Active Record Associations RailsGuide,

When you declare a has_and_belongs_to_many association, the declaring class automatically gains 16 methods related to the association:

...
collection<<(object, ...)
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment