gpt4 book ai didi

ruby-on-rails - rails : Finding all Users whose relationship has a specified attribute

转载 作者:行者123 更新时间:2023-12-04 20:08:04 25 4
gpt4 key购买 nike

我有三个模型:

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( bool 值)

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

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

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

但我觉得有更好的方法。

最佳答案

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

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' })
#^^^ ^

类似问题:

关于ruby-on-rails - rails : Finding all Users whose relationship has a specified attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25210569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com