【问题标题】:How to group by attribute but display value of nested attribute?如何按属性分组但显示嵌套属性的值?
【发布时间】:2020-08-03 08:34:56
【问题描述】:

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

如何做到这一点?

感谢您的帮助。

【问题讨论】:

    标签: sql ruby-on-rails ruby activerecord


    【解决方案1】:

    您应该尝试在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}")
    

    【讨论】:

    • @Tintin81 值得第二次尝试,所以我在阅读了 ActiveRecords 后编辑了答案,但想法总是一样的,您需要加入 People 并为每个客户安排一个人.
    • @Guiseppe Schembri:非常感谢。我想我现在走在正确的轨道上。它似乎有效,但我明天会用新的眼光再看一遍。 .uniq 是不必要的,但会破坏代码。
    • @Tintin81 很高兴你能找到正确的轨道。只是为了将来参考,我建议uniq 因为我认为如果你为"clients.id", "people.last_name" 分组,sum of payments 可能会被高估。无论如何,如果您将来需要这样复杂的查询,您可能需要解决Arel,看看this SO 帖子和suggested library,它可能非常有用。
    • 非常感谢您的帮助,@Giuseppe Schembri。上面的代码对我有用,所以我会将其标记为正确答案。
    猜你喜欢
    • 2020-12-01
    • 2019-07-29
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多