简体   繁体   English

Rails-从has_many中选择额外的字段:通过模型

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM