如何按属性分组但显示嵌套属性的值?

How to group by attribute but display value of nested attribute?

我的 Rails6 应用程序中有这些模型:


class Client < ApplicationRecord

  belongs_to :account

  has_many :people

end

class Person < ApplicationRecord

  belongs_to :client

end

class Payment < ApplicationRecord

  belongs_to :client

end

在我的 SharesController 中,我试图为每个 client 生成 总付款 并将它们显示为饼图:

class SharesController < ApplicationController

  def index

        @clients = current_account.clients.joins(:payments)
                                          .where(:payments => {:date => @range, :currency => @currency})
                                          .order("sum_payments_#{@part} DESC")
                                          .group("clients.id", "clients.name")
                                          .having("sum_payments_#{@part} > 0")
                                          .sum("payments.#{@part}")
      end

end

问题是它按 client 正确分组。但是,我不想显示每个客户的 name,而是显示每个客户的第一个嵌套 person.

last_name

如何做到这一点?

感谢您的帮助。

您应该尝试在 ClientPerson 之间创建连接,然后使用 uniq 以避免重复的客户端。

您可以尝试这样的操作(我不确定这段代码是否有效,但只是为了更清楚地说明我的意思)


@clients = current_account.clients.joins(:payments, :people)
                   .where(:payments => {:date => @range, :currency => @currency})
                   .order("sum_payments_#{@part} DESC")
                   .group("clients.id", "people.last_name")
                   .having("sum_payments_#{@part} > 0")
                   .sum("payments.#{@part}")