Rails join table ultimate tutorial

This is complete tutorial for creating join table in ruby on rails. It will show how to generate model, how to address associations, and join table model. Also will show you how to write form with multiple select boxes and how to handle it in controller.

First let's create join table in rails way, with city and cleaner as references.

rails g model Assignment city:references cleaner:references

This will create migration:

create_assignments.rb

class CreateAssignments < ActiveRecord::Migration
  def change
    create_table :assignments do |t|
      t.references :city, index: true, foreign_key: true
      t.references :cleaner, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

cleaner.rb

class Cleaner < ActiveRecord::Base
  has_many :assignments
  has_many :cities, through: :assignments
end

city.rb

class City < ActiveRecord::Base
  has_many :assignments
  has_many :cleaners, :through => :assignments
end

assignment.rb

class Assignment < ActiveRecord::Base
  belongs_to :city
  belongs_to :cleaner
end

cleaners_controller.rb

private

def cleaner_params
  params.require(:cleaner).permit(city_ids: [])
end

_form.html.erb Select multiple form

<%= form_for(@cleaner) do |f| %>
  <p>
    <%= f.label :cities %><br />
    <% for city in City.all %>
      <%= check_box_tag "cleaner[city_ids][]", city.id, @cleaner.cities.include?(city) %>
      <%=h city.name %><br />
    <% end %>
  </p>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>