This will 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 table in Rails way, with the city and the cleaner as references.
rails g model Assignment city: references cleaner: references
This will create the migration:
class CreateAssignments < ActiveRecord::Migration
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
has_many: cities, through :: assignments
,: through =>: assignments end
params.require (: cleaner) .permit (city_ids: )
_form.html.erb Select multiple form
<% = form_for (@cleaner) do | f |%>
<% = f.label: cities%>
<% for city in City.all%>
<% = check_box_tag "cleaner [city_ids] [city], city.id, @ cleaner.cities.include? (city)%>
<% = h city.name%>
<% = f.submit%>
Hope you find this tutorial helpful!
Originally posted at kolosek.com .