If You “Build” It, He Will Come…

… or, in this case, they will relate!

ActiveRecord Associations in Rails work wonders. If you’ve had some experience with them before, then it should be breeze. Rails additionally offers some wonderful association macros called collection associations to tidy up the process of relationships.

Let’s lay out two bare-bones models:

# has_many, belongs_to relationship #
class Artist < ActiveRecord::Base
has_many :songs
class Song < ActiveRecord::Base
belongs_to :artist

Great! Assuming the foreign key is already in place (in this case, artist_id) into the songs table, let’s go ahead and create some records. You may want to do this:

new_song = Song.new(artist_id: @artist.id, title: "Thriller")

Familiar, right? Well, with Rails, we get a lovely macro that shortens this down and saves some time:

new_song = @artist.songs.build(title: "Thriller")

“Build” takes on the task of creating an object of the associated class (Song) because of the relationship via the foreign key. You still have to save it. Not bad, eh?

Now if we wanted to do it the opposite way, on the “belongs_to” class (Artist), we normally would do something like this:

@song.artist = Artist.new(name: "Michael Jackson")

We can still alter this with the “build” macro, but because of the “belongs_to” relationship, it needs to be coded like this:

new_artist = @song.build_artist(name: "Michael Jackson")

“Build_” does essentially the same as “build” — it creates an object of the associated class. Just as with “build,” you still need to save!

Same concept, new lens…but oh the convenience!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.