Rails join table: Ultimate tutorial

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:

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], city.id, @ cleaner.cities.include? (city)%> 
      <% = h city.name%> <br /> 
    <% end%> 
  </ p> 
  <div class = "actions"> 
    <% = f.submit%> 
  </ div> 
<% end%> 

Hope you find this tutorial helpful!

 Originally posted at kolosek.com .

转载于:https://my.oschina.net/u/3772078/blog/1615121

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值