Rails:基于另一个表中的属性对一组SQL记录进行排序和显示

时间:2018-07-10 18:38:38

标签: ruby-on-rails postgresql

我想向用户显示其在给定月份内应付款的所有帐户的列表。这很容易做到:

@accounts = @user.accounts.joins(:payments)
  .where("due_date >= ?", Time.now.beginning_of_month)
  .where("due_date < ?", Time.now.beginning_of_month + 1.months)

但是,我想根据帐户类型(有4种类型)对付款进行分组和排序。另外,某些帐户在一个月内有多个应付款,我想为每个付款单独显示一行。

这是一个示例视图:

Type A Accounts
  Account 1: Payment due July 3
  Account 2: Payment due July 5
  Account 1: Payment due July 10    

Type B Accounts
  Account 3: Payment due July 6
  Account 4: Payment due July 11

Type C Accounts
...

本质上,我向用户显示了“付款”列表,但根据“帐户”类型对它们进行了排序。我尝试了各种解决方案,但似乎都不是理想的。什么是最有效,最“滑轨”的方式?

class User
  has_many :accounts
end

class Account
  has_many :payments
  belongs_to :user

  # acc_type = "A", "B", "C", or "D"
end

class Payment
  belongs_to :account

  # due_date
end

0 个答案:

没有答案