简体   繁体   中英

Rails: Model associations

I have two models, one called User and another called Recruiter. What I would like to do is to be able to create a scope that searches users and returns the results so recruiters can see them. But I'm not sure how to go about setting up the association. I made a through association between users and recruiters and created a new join table called recruiter_users but I'm not sure if this is the correct approach.

1) What the best way to make the association between the 2 models 2) how exactly would I display the user results in the recruiters view?

  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

Again, without having more details about your application, if all you need to do is display the User s associated with a particular Recruiter in a view, it could be as simple as this:

<% @recruiter.users.each do |user| %>
  <%= user.whatever_attribute %>
<% end %>

It sounds like you want your average run of the mill many to many association:

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

You don't have to name your join models a + b. If there is a more descriptive name of what the relation is use it.

this would let you iterate through the users recruited by a recruiter by:

@recruiter = Recruiter.includes(:recruited_users).find(params[:id])

<% @recruiter.recruited_users.each do |user| %>
  # ...
<% 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