[英]Rails belongs_to and has_many foreign_key relationship
I need a little help... I have these relationships... Users belong to Department, a Department has a manager, Managers (Users) can have many managed departments. 我需要一点帮助...我有这些关系...用户属于部门,一个部门有一个经理,经理(用户)可以有多个受管部门。
I'm having one of those days and I can't for the life of me figure out what to put inside the User
model to define the `has_many :managed_departments' part of the relationship. 我有一段日子,我一生都无法弄清楚在
User
模型中放置什么来定义关系的“ has_many:managed_departments”部分。
Department 部
class Department < ActiveRecord::Base
has_many :users
belongs_to :manager, foreign_key: "manager_id", class_name: "User"
end
User 用户
class User < ActiveRecord::Base
belongs_to :department
# has_many :managed_departments
end
This works: Department.last.manager
which returns: 这有效:
Department.last.manager
返回:
=> #<User id: 2, etc...
I'm having a mindblank on what to put in the User
model. 我对在
User
模型中放置什么内容不屑一顾。
Can anyone help? 有人可以帮忙吗?
You can use class_name
option same like you used it in Department
model 您可以像在
Department
模型中一样使用class_name
选项
#user.rb
class User < ActiveRecord::Base
belongs_to :department
has_many :managed_departments, class_name: "Department", foreign_key: "manager_id"
end
You are not creating right association. 您没有创建正确的关联。 You have many to many relation ship between user and department.
您在用户和部门之间有多对多关系。
user has_many departments (Can manage multiple department)
department has_many users
As a database standard you should break many to many relationship and introduce a new intermediate table. 作为数据库标准,您应该打破多对多关系并引入一个新的中间表。
So your new table should be users_departments
. 因此,您的新表应为
users_departments
。 In this table you can add column user is manager or not. 在此表中,您可以添加列用户是不是经理。
table should have column : user_id , department_is, is_manager 该表应具有列:user_id,department_is和is_manager
class Department < ActiveRecord::Base
has_many :users, :through => :users_departments
end
class User < ActiveRecord::Base
has_many :departments, :through => :users_departments
end
class UsersDepartment < ActiveRecord::Base
belongs_to :user
belongs_to :department
end
Here you can find anything with association. 在这里,您可以找到与关联相关的任何内容。 and with simple scope you can find manager of department also.
而且范围很简单,您还可以找到部门经理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.