Ho bisogno di portare una serie di oggetti rubino in JSON. Dovrò trovare l'oggetto nell'oggetto JSON per id, quindi penso che sia meglio che l'id sia la chiave di ogni oggetto. Questa struttura ha più senso per me:
{
"1": {"attr1": "val1", "attr2": "val2"},
"2": {"attr1": "val1", "attr2": "val2"},
"3": {"attr1": "val1", "attr2": "val2"}
}
In questo modo posso facilmente chiamare nell'oggetto JSON come console.log(json_obj[id].attr1)
Il problema è che non sono abbastanza sicuro su come costruire questo in rubino. Questo è quanto ho ottenuto:
# in ruby
@book_types = []
BookType.all.each do |bt|
@book_types << {bt.id => {:attr => bt.attr}}
end
@book_types = @book_types.to_json
// In JS
var bookTypes = JSON.parse("<%=raw @book_types %>");
2 domande: come posso costruire questo in rubino? C'è un modo migliore per realizzare ciò che sto facendo?
Anche solo una nota che sto costruendo questo sul framework Rails
Grazie!
risposte:
10 per risposta № 1Supponendo che BookType sia una classe ActiveRecord, puoi fare questo:
BookType.all(:select => "attr1, attr2").to_json
...dove "attr1, attr2"
è un elenco degli attributi che desideri includere nel tuo JSON.
Se vuoi il id
s come chiavi, puoi farlo invece:
BookType.all.inject({}) { |hsh, bt|
hsh[bt.id] = { "attr1" => bt.attr1, "attr2" => bt.attr2 }
hsh
}.to_json