问题描述
我有三个模型:
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_id
、roster_id、
和 pending
(布尔值)
The Rosterplayer table has three columns: user_id
, roster_id,
and pending
(boolean)
问题:给定一个名册,我将如何检索当前待处理的所有用户?
Question: Given a roster, how would I retrieve all users that are currently pending?
尝试:我的第一次尝试是遍历名册中的所有用户:
Attempt: My first attempt was to loop through all the users in the roster:
@team.rosters[0].users.each do |u|
Rosterplayer.find_by(roster_id: rosters[0].id, user_id: u.id, pending: true)
end
但我觉得有更好的方法.
But I feel like there is a better way of doing it.
推荐答案
您可以通过执行以下操作来实现:
You can achivete this by doing the following:
User.includes(:rosterplayers).where(rosterplayers: { pending: true })
这将返回所有具有至少 1 个 rosterplayer
且 pending
设置为 true
的用户记录.
This will return all User records having at least 1 rosterplayer
having pending
set to true
.
将查询限制为特定的 roster
实例:
Limit the query to a specific roster
instance:
User.includes(:rosterplayers).where(rosterplayers: { pending: true, roster_id: your_roster_id })
# your_roster_id can actually be an array of IDs
附加说明:小心使用 .joins 和 .includes:
Additional note: Be carefull with .joins and .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' })
#^^^ ^
类似问题:
- 可能未找到已命名的关联Rails 关联中的拼写错误问题
- Rails 活动记录查询与存在"的关联一个>
- Rails 3, has_one/has_many withlambda 条件
- Rails 4 范围来查找父母没有孩子
- 加入具有活动记录的多个表
这篇关于Rails:查找关系具有指定属性的所有用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!