【问题标题】:Rails using 'where' on a model that has a has_many relationshipRails 在具有 has_many 关系的模型上使用“where”
【发布时间】:2021-02-18 08:03:12
【问题描述】:

我有两个模型,AccountUser

class Account
  has_many :users
end

class User
  belongs_to :account
end

我的问题的相关模型详细信息是:

  • 每个帐户都有一个subscription 类型,可以是standardpremiumenterprise

如何正确列出属于premium 帐户的所有Users?此外,我如何在 all premium 帐户中列出所有用户,因为可以有任意数量的 premium 帐户。

我尝试了以下几种变体:

Account.where(subscription: "premium").users # undefined method users

User.where(subscription: "premium") # returns nothing

Account.where(subscription: "premium").each do |account|
  account.users # seems to return an array?
end

【问题讨论】:

  • 请不要同时提出多个问题,而是创建一个单独的问题。

标签: ruby-on-rails ruby activerecord activemodel


【解决方案1】:

你想要的是左内连接:

User.joins(:account)
    .where(accounts: { subscription: "premium" })

这将返回用户表中与联接表匹配的所有记录。

如何正确列出属于高级帐户的所有用户?

如果您的意思是属于特定帐户的用户,您可以在该特定帐户上调用 #users 方法。

account = Account.eager_load(:users).find(1)
account.users

【讨论】:

    【解决方案2】:

    第一个问题:

    列出属于高级帐户的所有用户:

    您的第一次尝试 (Account.where(subscription: "premium").users) 不起作用,因为 Account.where(subscription: "premium") 已经返回了许多帐户,因此是一个列表(更准确地说是一个 ActiveRecord 关系对象)并且您不能在该列表上调用 .users。一个账号只能拨打.users 你需要的是一个join 语句来连接两个表。你可以在这里阅读更多信息:https://guides.rubyonrails.org/active_record_querying.html#joining-tables 既然你想要用户,你应该从用户开始。

    您的查询应该如下所示:

    User.joins(:account).where(accounts: {subscription: "premium"})
    

    这将为您提供所有拥有订阅类型高级帐户的用户。

    我认为您关于查询的第二个问题实际上是相同的

    此外,我如何列出所有高级帐户中的所有用户,因为可以有任意数量的高级帐户。

    【讨论】:

      【解决方案3】:

      其他答案很好,另一个选择是Account 模型

      scope :premium, -> { where(subscription: 'premium') }
      

      和你的查询

      User.joins(:account).merge(Account.premium) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多