【问题标题】:How to navigate multiple layers of parent-child relationships using ActiveRecord如何使用 ActiveRecord 导航多层父子关系
【发布时间】:2021-04-13 21:06:51
【问题描述】:

标题含糊不清,有些误导,我深表歉意。 Rails 新手,这个问题对我来说有点复杂,甚至无法创建一个概括的描述。

我正在处理一项任务,其中有 4 个表与我交互,即 Merchants、Customers、Invoices 和 transactions。 Here is a picture of my db schema 这是我的模型:

class Merchant < ApplicationRecord
    has_many :invoices
    has_many :customers, through: :invoices
    has_many :items
end

class Customer < ApplicationRecord
    has_many :invoices
    has_many :merchants, through: :invoices
end

class Invoice < ApplicationRecord
  belongs_to :customer
  belongs_to :merchant
  has_many :transactions
  has_many :invoice_items
  has_many :items, through: :invoice_items
  enum status: [:"in progress", :completed, :cancelled]
end

class Transaction < ApplicationRecord
  belongs_to :invoice
  enum result: [:success, :failed]
end

事务的状态为“成功”或“失败”,分别由整数枚举“0”或“1”表示。我的目标是使用活动记录查询为任何给定商家找到交易最成功的前五名客户。到目前为止,我还没有找到一种方法来访问商家的交易,反之亦然。我已经能够编写一些有用的代码,例如在所有商家中找到前 5 名客户:

Transaction
.joins(invoice: :customer)
.joins(invoice: :merchant)
.select('customers.*, count(transactions) as total_success')
.where('transactions.result = ?', 1)
.group('customers.id')
.order('total_success DESC')
.limit(5)

但任何将其绑定到特定商家 ID 的尝试都会产生错误,因为交易对商家一无所知。

我最初将作业解释为只需要获取完整的发票并计算出我认为可能接近但仍需要一种与交易交互的方式的代码:

in the merchant model

self.invoices.group(:customer_id).where(status: 1).count.sort_by{|k, v| v}.reverse.first(5)

如果有人能指出我正确的方向,我将不胜感激。如果这个问题已经在其他地方得到回答,我再次道歉,但我几乎不知道如何问它:/

【问题讨论】:

  • 您可能会后悔使用 :"in progress" 而不是 :in_progress 这样的符号。
  • 一开始我没有注意到这一点,但我同意你的看法,不幸的是,该部分已经内置到项目中

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

我会以商家而不是交易作为起点,因为您想在任何给定的商家上运行一些逻辑。 所以我会从寻找商家开始,包括发票和他们的成功交易。像这样的:

merchant =
 Merchant
 .includes(invoices: [:transactions])
 .where(id: 1, transactions: { result: :success } )

因此,这将为您提供变量merchant,它是一个数组,其中包含 1 个商家及其所有发票和成功交易。现在您应该可以按交易数量来订购发票(想想.length)并获取前 5 个(或最后 5 个,具体取决于您如何订购)。 现在有了这 5 张发票,您可以打电话给客户,因为发票属于客户。

【讨论】:

  • 感谢您的帮助!每当我运行此程序时,我都会收到一个错误,即我无法将符号转换为整数(尝试执行 :invoices[:transactions] 时),也不允许我在 Merchant.find(1) 上使用 .includes 说它没有不能处理该类的对象。我正在尝试在 Rails 控制台中运行它,这会是问题吗?
  • 我编辑了我的答案。这应该会给你一个更好的结果。
  • 谢谢!这真的很有帮助,我能够从中找出答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多