ruby-on-railsruby-on-rails-3.2

how to return a Rails query as a hash with the keys as the primary key id value


I'm curious whether there is native way to return a query with the id value as the hash key returned. Something like:

Location.find([2,4,7]).as_hash

get back

{
  2:{name:"name 1", id: 2},
  4:{name:"name 4", id: 4},
  7:{name:"name 7", id: 7},

}

I'd like to just do a to_json and this would be convenient.

thx


Solution

  • I'd like to just do a to_json and this would be convenient.

    Natively, There is a to_json method which can directly give you the output of query in json format.

    Location.find([2,4,7]).to_json
    

    However, the format is different from what you have specified. Check if it works for you.

    to_xml, to_yaml methods are other methods which can similarly output xml and yaml data, respectively, from the activerecord queries.

    Alternatively, you can do something like this

    locations = Location.find([2,4,7])
    locations_hash = {}
    locations.each do |location|
        locations_hash[location.id] = location 
    end
    locations_hash.to_json