[英]Rails: Model associations
我有两个模型,一个叫做User,另一个叫做Recruiter。 我想做的是能够创建一个范围来搜索用户并返回结果,以便招聘人员可以看到他们。 但是我不确定如何建立关联。 我在用户和招聘人员之间建立了直通关联,并创建了一个新的联接表,称为招聘者用户,但是我不确定这是否正确。
1)在两个模型之间建立关联的最佳方式是什么?2)我将如何在招聘者视图中准确显示用户结果?
class RecruiterUser < ApplicationRecord
# this is a join model between recruiters and users
belongs_to :recruiter
belongs_to :user
class User < ApplicationRecord
# creates association with recruiters model through the join table recruiter_users
has_many :recruiter_users
has_many :recruiters, through: :recruiter_users
class Recruiter < ApplicationRecord
# creates association with users model through the join table recruiter_users
has_many :recruiter_users
has_many :users, through: :recruiter_users
同样,如果没有关于您的应用程序的更多详细信息,如果您需要做的就是在视图中显示与特定Recruiter
关联的User
,则可能会像这样简单:
<% @recruiter.users.each do |user| %>
<%= user.whatever_attribute %>
<% end %>
听起来您想让工厂的平均运转多对多关联:
class User
has_many :recruitments
has_many :recruiters,
through: :recruitments
end
class Recruiter
has_many :recruitments
has_many :recruited_users,
through: :recruitments,
source: :user
end
class Recruitment
belongs_to :user
belongs_to :recruiter
end
您不必将联接模型命名为a + b。 如果对关系有更描述性的名称,请使用它。
这将使您通过以下方式遍历招聘人员招聘的用户:
@recruiter = Recruiter.includes(:recruited_users).find(params[:id])
<% @recruiter.recruited_users.each do |user| %>
# ...
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.