Rails join table: Ultimate tutorial

2018-01-30 10:42:13来源:oschina作者:Kolosek人点击

分享
第七城市th7cn

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
endcleaner.rb
class Cleaner has_many: assignments
has_many: cities, through :: assignments
end
city.rb
class City has_many: assignments
has_many: cleaners
,: through =>: assignments end
assignment.rb
class Assignment 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], city.id, @ cleaner.cities.include? (city)%>
<% = h city.name%>

<% end%>


<% = f.submit%>

<% end%>

Hope you find this tutorial helpful!


Originally posted at kolosek.com .

第七城市th7cn

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台