Understanding How to Return a Hash Format Response in an Array from an Aggregation Function

Asked 2 years ago, Updated 2 years ago, 97 views

I'd like to submit JSON's response as follows, but it's clogged up.
Could you give me some advice?

Currently

[["book", 10], ["pen", 100]]

Goals

[
 {
  category:book
  amount —10
 },
 {
  category:pen
  amount: 100
 }
]

Current State Source

controller

def index
 @category_history=CategoryHistory.all.group(:category).sum(:amount)
end

json.builder

json.array!@category_history

ruby-on-rails ruby json

2022-09-30 19:20

1 Answers

How about this one?

#json.builder
json.array!@category_history do|ch|
  json.category ch[0]
  json.amountch[1]
end

As for jbuilder, there are many samples written on README, so if you get lost, you can look at it

https://github.com/rails/jbuilder


2022-09-30 19:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.