This is a complete tutorial for creating join table in Ruby on Rails. It will show you how to:
- generate the model,
- address associations and
- join table model.
Also, it will show you how to write a form with multiple select boxes and how to handle it in the controller.
First, let's create join tables in Rails way, with the city and the cleaner as references.
rails g model Assignment city:references cleaner:references
This will create the 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 %>
Hope you find this post helpful!
Originally posted at kolosek.com.