Rails magic: Managing join models with has_many through - Rails

When you're new to Ruby on Rails you can find yourself accidentally building things that your framework already provides for you. Here's an example of some magic you should know about to avoid reinventing the wheel.

Say you have a Movie model set up like this:

class Movie < ActiveRecord::Base hasmany :taggings hasmany :tags, through: :taggings end

class Tagging < ActiveRecord::Base belongsto :movie belongsto :tag end

class Tag < ActiveRecord::Base has_many :taggings end

Rails gives you an easy way to manage the Movie's tags without having to deal with the Taggings join table:

> movie = Movie.first => # > tag = Tag.first => #

Instead of worrying about making a Tagging, you can just do:

> movie.tags = [tag] or > movie.tag_ids = [3]

And Rails will automatically make the tagging for you:

> movie.save => true > movie.tags => #]> > movie.taggings => #]>

This makes using tools like Chosen or Select2 to manage adding/removing things like tags very simple:

<%= formfor movie do |f| %> ... <%= f.collectionselect :tagids, Tag.all, :id, :tos, { include_blank: true }, multiple: 'multiple', class: 'chosen' %> ... <% end %>

Max Holder

Max is a former SciMed developer.