Pergunta

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?

Foi útil?

Solução

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

Outras dicas

This question is pretty old, but 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

You can do it like this way

Jbuilder.encode do |json|
  json.service_issues @service.issues.inject({}) { |hash, issue| hash[issue.id] = issue.name; hash }
end 

The code generating hash technique may be understood by following example.

[1] pry(main)> array = [{id: 1, content: 'a'}, {id: 2, content: 'b'}]
=> [{:id=>1, :content=>"a"}, {:id=>2, :content=>"b"}]
[2] pry(main)> array.inject({}) { |hash, element| hash[element[:id]] = element[:content]; hash }
=> {1=>"a", 2=>"b"}

The key point of inject to generate hash, return created hash every after inserting new element. Above example, it is realized by ; hash.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top