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

时间:2014-12-09 13:59:50

标签: ruby-on-rails has-many-through

我有以下结构

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

我为加入的模型添加了一个额外的字段:teammates - > 待:布尔

我想要做的是显示一个项目,其中包括具有布尔值的用户,以了解每个用户是否仍处于未决状态。

编辑:查询如下所示:

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

1 个答案:

答案 0 :(得分:0)

我会做这样的事情:

@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
相关问题