Ruby on rails 模型关联上的Rails where()子句?

Ruby on rails 模型关联上的Rails where()子句?,ruby-on-rails,Ruby On Rails,假设我有一个帐户模型,它有许多用户。帐户有一个布尔“活动”列。如何获取属于“活动”帐户的所有用户 @users_of_active_accounts = User.? 谢谢 试试这个: User.joins(:account).where(:accounts => { :active => true }) Account.includes(:users).where(active: true) 您需要加入accounts表并合并相应的帐户范围: User.joins(:acco

假设我有一个帐户模型,它有许多用户。帐户有一个布尔“活动”列。如何获取属于“活动”帐户的所有用户

@users_of_active_accounts = User.?
谢谢

试试这个:

User.joins(:account).where(:accounts => { :active => true })
Account.includes(:users).where(active: true)

您需要加入accounts表并合并相应的帐户范围:

User.joins(:account).merge(Account.where(:active => true))

在帐户模型的关联中使用where子句:

class Account < ActiveRecord::Base
  has_many :users, -> {where(active: true)}
第三次更新: 下面是一个示例用户模型,它具有active_users属性

class User < ActiveRecord::Base
  belongs_to :account
  def self.active
    where(account: Account.where(active: true))
  end
end

一块存在于此的宝石:(我是作者)

有了它,您可以通过以下方式做您想做的事情:

@users_of_active_accounts = User.where_assoc_exists(:account, active: true)
@users_of_active_accounts = User.where_assoc_exists(:account, &:active)
如果您帐户上有active的作用域,您可以这样称呼它:

@users_of_active_accounts = User.where_assoc_exists(:account, active: true)
@users_of_active_accounts = User.where_assoc_exists(:account, &:active)
因此,如果您愿意,现在可以为以下内容创建一个很好的范围:

class User < ActiveRecord::Base
  belongs_to :account

  scope :active_account, -> { where_assoc_exists(:account, active: true) }
end

@users_of_active_accounts = User.active_account
class用户{where\u assoc\u存在(:account,active:true)}
结束
@活动帐户的用户=用户。活动帐户
阅读更多的文章。这是一个and。

试试这个:

User.joins(:account).where(:accounts => { :active => true })
Account.includes(:users).where(active: true)

你想让所有活动帐户的所有用户都在一个平面数组中吗?如果你有一个命名范围,你也可以使用一个命名范围,例如
User.joins(:account).merge(account.active)
Awesome,这将是我的下一个问题。谢谢@SimonPerepelitsa应该是
:accounts
?在模式中,我如何添加order by还具有{u many:users,->{where(active:true)}您可以直接在where函数之后添加它:has{u many:users,->{where(active:true).order(:name)}。基本上,任何活动记录查询都可以放在该闭包中,但由于范围的原因,使用变量可能会很棘手。有一种方法可以传入范围,以便能够在关联中使用变量。但不确定文档在哪里。我相信第三次更新可以作为一个范围来编写
scope:active,->{where(account:account.where(active:true))}
谢谢@evanthegrayt,我对rails的这一部分不太熟悉。我必须对此进行研究。有用的文章回顾范围: