ruby-on-railsjsonjbuilder

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?


Solution

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