我有三种模式:
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
(布尔值)
问题:给定一个名单,如何检索当前待处理的所有用户?
尝试:我的第一次尝试是遍历名单中的所有用户:
@team.rosters[0].users.each do |u|
Rosterplayer.find_by(roster_id: rosters[0].id, user_id: u.id, pending: true)
end
但我觉得有更好的方法。
答案 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' })
#^^^ ^
类似问题: