JBuilder loop that produces hash

Jonas picture Jonas · Apr 9, 2013 · Viewed 14k times · Source

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?

Answer

Pavel Pravosud picture Pavel Pravosud · Apr 10, 2013

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 ] }]