简体   繁体   中英

Select tag and Many to Many Relation in Rails 4.0

In my project i have 2 models Employee.rb

class Employee < ActiveRecord::Base
  has_many :shop
  ..
  ..
  ..
end

and Shop.rb

class Shop < ActiveRecord::Base
  has_many :employees
  ..
  ..
  ..
end

I'm not sure whether this relation is right or not. The working should be like this. Employee got a foriegn key employeeID which is used in many tables.. If an employee has got more than 4 shops then 4 entries of the same employee will be in the employee table(employeeID will be same for all) and so on. Now my issue is I have a form which updates the employee details. Form is used to create as well as edit employee details. I want to put a select tag in this form which shows all the shops. On edit page the shops that belongs to the user should be preselected..

How to do this? Help

You should use the has_and_belongs_to_many association:

在此处输入图片说明

--

Has And Belongs To Many

This will mean creating a new table:

#employees_shops
employee_id | shop_id

You can then associate the two models using the has_and_belongs_to_many declaration:

#app/models/employee.rb
Class Employee < ActiveRecord::Base
    has_and_belongs_to_many :shops
end

#app/models/shop.rb
Class Shop < ActiveRecord::Base
    has_and_belongs_to_many :employees
end

This will allow you to call:

@shop.employees.each do |employee|
    employee.name
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM