【问题标题】:Rails: Finding all Users whose relationship has a specified attributeRails:查找关系具有指定属性的所有用户
【发布时间】:2014-08-09 03:14:35
【问题描述】:

我有三个模型:

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

但我觉得有更好的方法。

【问题讨论】:

  • 显示pending?方法
  • 我修复了上面的帖子以使其更清晰

标签: ruby-on-rails


【解决方案1】:

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

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

这将返回至少有 1 个 rosterplayerpending 设置为 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' })
                #^^^           ^

类似问题:

【讨论】:

  • 鉴于用户可以在多个名册上,我如何将查询限制为一个指定的名册(即team.rosters[0])?
  • 我更新了我的答案以满足您的要求。这是一个简单的where 子句添加到查询中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多