Abdul Baig
Abdul Baig

Reputation: 3721

making hash to produce JSON

I am creating a hash which would produce JSON to be used in APIs.

To make Hash I am trying this:

presses = Press.select(:id, :name)
pulls = Pull.select(:id, :name)
response = {list: {presses: presses, pulls: pulls}}

Actually works good and produces:

{"list":{
  "presses":[
     {"id":1,"name":"p40"},
     {"id":2,"name":"p41"}],

  "pulls":[
     {"id":1,"name":"Best Effort"},
     {"id":2,"name":"First Good"}]
}}

But the requirement has changed to make it like:

{"list":{
  "presses":[
     {"id":1,"name":"p40"
     "pulls":[
       {"id":1,"name":"Best Effort"},
       {"id":2,"name":"First Good"}]},

     {"id":2,"name":"p41"
     "pulls":[
       {"id":1,"name":"Best Effort"},
       {"id":2,"name":"First Good"}]},
     ],
}}

Note Each press object should contain all pull object. So far don't know how to achieve this. Any Idea?

Upvotes: 1

Views: 32

Answers (2)

floomby
floomby

Reputation: 301

This will do what you want

pulls = Pull.select(:id, :name)
presses = Press.select(:id, :name)
presses = presses.collect do |press|
    press.merge({pulls: pulls})
end
response = {list: {presses: presses}}

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118271

I think this is Rails question. Thus I have #attributes method. Here is my attempt

presses = Press.select(:id, :name)
pulls = Pull.select(:id, :name)

response = { list: {
  presses: presses.map do |press|
    press.attributes.merge(pulls: pulls.map(&:attributes))
  end
}
}.to_json

Upvotes: 1

Related Questions