For Ruby >= 2.0 or Ruby < 2.0 with backports:
Item.all.map { |r| [r.id, r.attributes] }.to_h
For Ruby < 2.0 without backports:
Hash[Item.all.map { |r| [r.id, r.attributes] }]
Pregunta
How to get records from the database with key=id
items = Item.all
Instead of:
items = {{"id"=>1, "title"=>"A"},
{"id"=>5, "title"=>"B"}}
How to get?
items = {"1"=>{"id"=>1, "title"=>"A"},
"5"=>{"id"=>5, "title"=>"B"}}
Solución
For Ruby >= 2.0 or Ruby < 2.0 with backports:
Item.all.map { |r| [r.id, r.attributes] }.to_h
For Ruby < 2.0 without backports:
Hash[Item.all.map { |r| [r.id, r.attributes] }]
Otros consejos
You can try the following :
result = {}
Item.all.collect{|item| result[item.id] = item.as_json}