Skip to content

Instantly share code, notes, and snippets.

@ashleygwilliams
Last active December 19, 2015 12:09
Show Gist options
  • Save ashleygwilliams/5952482 to your computer and use it in GitHub Desktop.
Save ashleygwilliams/5952482 to your computer and use it in GitHub Desktop.

Flexing Associations in Rails

Objectives

  • Be comfortable building and associating objects via all mechanisms available

Instructions

  1. Create 3 models: Artist, Album, and Song

  2. The artist, "Wu-Tang Clan", has the following album, with the following songs:

    • "36 Chambers"
      1. "Bring da Ruckus"
      2. "C.R.E.A.M"
      3. "Protect Yo Neck"
      4. "Method Man"

Add each song to the album in a different way. e.g. using an example where an Author has many Posts: Post.build, posts << Post.new, Author.build_post

  1. The artist, "Notorius B.I.G.", has the following albums, with the following songs.

    • "Ready to Die"

      1. "Gimme the Loot"
    • "Born Again"

      1. "Dead Wrong"
    • "Life After Death"

      1. "Hypnotize"

Add the albums through a song, and add artists through album, via .build_*, push (shovel <<), or assignment.

@ningbit
Copy link

ningbit commented Jul 9, 2013

I'm pretty sure the Author/Post example is reversed, should be Post.build_author and the first is not clear, should be author.posts.build

Here's the doc that helped me:
http://guides.rubyonrails.org/association_basics.html

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