首页 > 解决方案 > 如何按属性分组但显示嵌套属性的值?

问题描述

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


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我不想显示每个客户的,而是想显示last_name每个客户的第一个嵌套的person.

如何才能做到这一点?

谢谢你的帮助。

标签: sqlruby-on-railsrubyactiverecord

解决方案


您应该尝试在 and 之间创建一个连接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}")

推荐阅读