【问题标题】:Multi-level database retrieval in RailsRails 中的多级数据库检索
【发布时间】:2019-01-01 16:21:41
【问题描述】:

我有三个 Rails 模型和关联:

class Account < ApplicationRecord
  has_many :bills
  belongs_to :user
end

class Bill < ApplicationRecord
  belongs_to :account
end

class User < ApplicationRecord
  has_many :accounts
end

我正在尝试创建一个端点来返回所有用户及其帐户以及帐户的所有账单。

现在我可以通过以下方式获取所有账单及其帐户:

bill_records = Bill.all.includes(:account)
bill_records_with_associations = bill_records.map do |record|
  record.attributes.merge(
  'account' => record.account,
  )

但现在我需要获取与每个帐户关联的用户,我不知所措。

我也可以在这里检索用户吗?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    发布的解决方案效果很好。但是,您可能希望通过此 ORM 查询利用预先加载和缓存与 User 对象关联的 Account 对象:

    bill_records = Bill.includes(:account => :user)
    

    这将缓存与查询的Account 对象关联的所有User 对象。然后,以下代码块仅使用上述查询的缓存结果,减少对您的数据库的额外 ORM 查询(bill_records = Bill.includes(:account) 仅缓存 Account 对象并对下面使用的每个 record.account.user 语句进行 ORM 查询)。

    bill_records_with_associations = bill_records.map do |record|
      record.attributes.merge(
        'account' => record.account,
        'user' => record.account.user
      )
    end
    

    【讨论】:

      【解决方案2】:

      这是我解决它的方法...

      bill_records = Bill.all.includes(:account)
      bill_records_with_associations = bill_records.map do |record|
        record.attributes.merge(
        'account' => record.account,
        'user' => record.account.user
        )
      end
      

      【讨论】:

        猜你喜欢
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        • 1970-01-01
        • 2016-02-09
        • 1970-01-01
        相关资源
        最近更新 更多