Last Updated: February 25, 2016
·
11.39K
· bengy

has_and_belongs_to_many (HABTM) associations in Rails 4

The HABTM association in Rails is a very powerful, clean way to define multiple cross associations between instances of two models.

Read up on it here to determine whether or not it's the best solution for your project. If it is, here's a quick tutorial on how to implement it.

Let's take an example where industries can have multiple sectors and sectors can belong to multiple industries.

In your industry.rb file (note - use plural references to your models when defining the association):

has_and_belongs_to_many :sectors

In your sector.rb file:

has_and_belongs_to_many :industries

Now create a table to map the associations (note - makes sure to use lowercase references to the models as this ensure the table name follows Rails' expected convention):

rails g migration CreateJoinTableIndustrySector industry sector

Let's assume that we only want to assign sectors to industries through the industry "_form" view so now update your view (note - this example uses slim and simple_form).

= simple_form_for(@industry) do |f|
   = f.input :name
   ...
   = f.association :sectors, as: :select
   = f.button :submit

and finally update your controller to account for strong params:

params.require(:industry).permit(:name, ... , sector_ids: [])

Now run "rake db:migrate" to create your join table, restart your server, and you're done :)