简体   繁体   中英

Rails - select extra field from has_many :through model

I have the following structure

class Project
  has_many :teammates
  has_many :users, :through => :teammates
end

class Teammate
  belongs_to :user
  belongs_to :project
end

class User
  has_many :teammates
  has_many :users, :through => :teammates
end

I added an extra field to the joining model: teammates -> pending:boolean

What I want to do is display a project including users with the boolean to know whether or not each user is still pending or not.

EDIT: the query looks like this:

Project.includes(:users).find(params[:id])

I'd like to be able to do something like:

class Project
  has_many :teammates

  # I tried this
  has_many :users, :through => :teammates, :select => 'users.*, teammates.*'
  # ERROR: Unknown key: :select

  # And this
  has_many :users, -> { select("users.*, teammates.pending") }, through: :teammates
  # ERROR: missing FROM-clause entry for table "teammates"
end

I'd do something like this:

@project = Project.find(params[:id])
@project.teammates.each do |teammate|
  # an example provided to show that you have access to `pending` field as well as all users fields:
  teammate.pending # pending field
  teammate.user # all user fields
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