controller.rb
def index
@expenses = Expense.all.order(:expense_type_id)
end
@expenses如下
[#<Expense:0x00007faeb044c6e8
id: 1,
amount: 120
expense_type_id: 1>,
#<Expense:0x00007faeb044c2b0
id: 2,
amount: 1200
expense_type_id: 1>,
#<Expense:0x00007faeb044c2b0
id: 3,
amount: 11200
expense_type_id: 3>,
#<Expense:0x00007faeb044c2b0
id: 4,
amount: 1120
expense_type_id: 4>,
#<Expense:0x00007faeb044c2b0
id: 5,
amount: 1120
expense_type_id: 4>]
index.json.jbuilder
json.records do
json.array! @expenses do |expense|
json.amount expense.billed
json.id expense.id
json.expense_type_id expense.expense_type_id
end
end
现在从index.json.jbuilder文件返回的输出是
records = [{amount: 120, id: 1, expense_type_id: 1}, {amount: 1200, id: 2, expense_type_id: 1}, {amount: 11200, id: 3, expense_type_id: 3}, {amount: 1120, id: 4, expense_type_id: 4}, {amount: 1120, id: 5, expense_type_id: 4}]
但我想要的输出是
records = [{amount: 120, id: 1, expense_type_id: 1}, {amount: 1200, id: 2, expense_type_id: 1}, {amount: sum of amount with expense_type_id 1, id: 'Subtotal', expense_type_id: nil}, {amount: 11200, id: 3, expense_type_id: 3}, {amount: sum of amount with expense_type_id 3, id: 'Subtotal', expense_type_id: nil}, {amount: 1120, id: 4, expense_type_id: 4}, {amount: 1120, id: 5, expense_type_id: 4}, {amount: sum of amount with expense_type_id 4, id: 'Subtotal', expense_type_id: nil}]
我希望插入一个Subtotal对象,以获取每个expense_type_id的所有费用。任何帮助都很感激。
2条答案
按热度按时间lx0bsm1f1#
我没有使用过json builder。我用ruby做的,希望你能翻译成builder格式。
polhcujo2#
我会采用面向对象的方法,通过定义一个名为
ExpenseType
的类(也许你的应用程序中已经有了这个,因为我看到了一个变量expense_type_id
)。现在,
ExpenseType
示例数组可以负责聚合和格式化它们的json表示,类似于...最后,每个
Expense
对象都知道如何将自己表示为json: