繁体   English   中英

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

[英]Rails - select extra field from has_many :through model

我有以下结构

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

我在加入模型中添加了一个额外的字段:队友-> 未决:布尔值

我想做的是用布尔值显示一个包含用户的项目,以了解每个用户是否仍在等待处理。

编辑:查询看起来像这样:

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

我希望能够执行以下操作:

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

我会做这样的事情:

@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