Rails join table ultimate tutorial

Kolosek 发布于22天前 阅读60次
0 条评论

This is a complete tutorial for creating join table in Ruby on Rails. It will show how to:

  • generate the model,
  • address associations and
  • join table model.

Also, this tutorial 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 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 %>

Hope you found this tutorial helpful!

Originally published at kolosek.com.

需要 登录 后回复方可回复, 如果你还没有账号你可以 注册 一个帐号。