簡體   English   中英

Rails:模型關聯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM