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

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

本文介绍了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(布尔值)

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 个 rosterplayerpending 设置为 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:查找关系具有指定属性的所有用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:46