Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JBuilder loop that produces hash

I need loop that produces hash, not an array of objects. I have this:

json.service_issues @service.issues do |issue|
  json.set! issue.id, issue.name
end

that results:

service_issues: [
  {
    3: "Not delivered"
  },
  {
    6: "Broken item"
  },
  {
    1: "Bad color"
  },
  {
    41: "Delivery problem"
  }
]

I need this:

service_issues: {
   3: "Not delivered",
   6: "Broken item",
   1: "Bad color",
   41: "Delivery problem"
}

Is it possible to do this without converting AR result to hash manually?

like image 588
Jonas Avatar asked Apr 09 '13 04:04

Jonas


2 Answers

Jbuilder dev here.

Short answer: Yes. It's possible without converting array of models into hash.

json.service_issues do
  @service.issues.each{ |issue| json.set! issue.id, issue.name }
end

but it'd probably be easier to prepare hash before-hand.

json.service_issues Hash[@service.issues.map{ |issue| [ issue.id, issue.name ] }]
like image 173
Pavel Pravosud Avatar answered Oct 19 '22 12:10

Pavel Pravosud


For anyone who is interested in having an hash of arrays (objects), you can use the following code:

@bacon_types.each do |bacon_type|
json.set! bacon_type.name, bacon_type.bacons do |bacon|
    bacon.title bacon.title
    ...
end
like image 38
KrauseFx Avatar answered Oct 19 '22 13:10

KrauseFx