Rails:查找其关系具有指定属性的所有用户

时间:2014-08-08 19:04:30

标签: ruby-on-rails

我有三种模式:

class User < ActiveRecord::Base
  has_many :rosterplayers
  has_many :rosters, -> { uniq } ,  :through => :rosterplayers
end

class Roster < ActiveRecord::Base
  has_many :rosterplayers
  has_many :users, -> { uniq }, through: :rosterplayers
end

class Rosterplayer < ActiveRecord::Base
  belongs_to :roster
  belongs_to :user
  validates :user_id, :uniqueness => { :scope => :roster_id }
end

Rosterplayer表有三列:user_idroster_id,pending(布尔值)

问题:给定一个名单,如何检索当前待处理的所有用户?

尝试:我的第一次尝试是遍历名单中的所有用户:

@team.rosters[0].users.each do |u|
  Rosterplayer.find_by(roster_id: rosters[0].id, user_id: u.id, pending: true)
end

但我觉得有更好的方法。

1 个答案:

答案 0 :(得分:4)

您可以通过执行以下操作来实现此目的:

User.includes(:rosterplayers).where(rosterplayers: { pending: true })

这将返回至少有rosterplayer pending设置为true的所有用户记录。

将查询限制为特定的roster实例:

User.includes(:rosterplayers).where(rosterplayers: { pending: true, roster_id: your_roster_id })
# your_roster_id can actually be an array of IDs

补充说明:请注意.joins和.includes:

# consider these models
Post 
  belongs_to :user
                #^^
User
  has_many :posts
               #^

# the `includes/joins` methods use the name defined in the model :
User.includes(:posts).where(posts: { title: 'Bobby Table' })
                  #^            ^
# but the `where` uses the pluralized version (table's name) : 
Post.includes(:user).where(users: { name: 'Bobby' })
                #^^^           ^

类似问题: