Rails中的多级数据库检索

时间:2018-07-24 23:22:22

标签: ruby-on-rails activerecord

我有三种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,
  )

但是现在我需要获取与每个帐户相关联的用户,我很茫然。

我是否也可以在此处检索用户?

2 个答案:

答案 0 :(得分:1)

发布的解决方案效果很好。但是,您可能想利用以下ORM查询来急切加载和缓存User对象中与Account对象相关的bill_records = Bill.includes(:account => :user) 对象:

User

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

CREATE AGGREGATE myagg(integer)
(
    INITCOND = '{ 0, 1 }',
    STYPE = integer[],
    SFUNC = myaggsfunc
);

答案 1 :(得分:0)

这是我解决的方法...

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