1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails join table: Ultimate tutorial

Posted at

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 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:

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| %>

<%= f.label :cities %>
<% for city in City.all %> <%= check_box_tag "cleaner[city_ids][]", city.id, @cleaner.cities.include?(city) %> <%=h city.name %>
<% end %>

<%= f.submit %>
<% end %>`

Hope you find this tutorial helpful!

Originally posted at kolosek.com.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?