How to convert ActiveRecord results into an array of hashes

后端 未结 3 2066
醉梦人生
醉梦人生 2020-12-04 06:29

I have an ActiveRecord result of a find operation:

tasks_records = TaskStoreStatus.find(
  :all,
  :select => \"task_id, store_name, store_region\",
  :co         


        
相关标签:
3条回答
  • 2020-12-04 07:22

    For current ActiveRecord (4.2.4+) there is a method to_hash on the Result object that returns an array of hashes. You can then map over it and convert to symbolized hashes:

    # Get an array of hashes representing the result (column => value):
    result.to_hash
    # => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
          {"id" => 2, "title" => "title_2", "body" => "body_2"},
          ...
         ]
    
    result.to_hash.map(&:symbolize_keys)
    # => [{:id => 1, :title => "title_1", :body => "body_1"},
          {:id => 2, :title => "title_2", :body => "body_2"},
          ...
         ]
    

    See the ActiveRecord::Result docs for more info.

    0 讨论(0)
  • 2020-12-04 07:29

    as_json

    You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

    tasks_records = TaskStoreStatus.all
    tasks_records = tasks_records.as_json
    
    # You can now add new records and return the result as json by calling `to_json`
    
    tasks_records << TaskStoreStatus.last.as_json
    tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
    tasks_records.to_json
    

    serializable_hash

    You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

    tasks_records = TaskStoreStatus.all
    tasks_records.to_a.map(&:serializable_hash)
    

    And if you want an ugly solution for Rails prior to v2.3

    JSON.parse(tasks_records.to_json) # please don't do it
    
    0 讨论(0)
  • 2020-12-04 07:29

    May be?

    result.map(&:attributes)
    

    If you need symbols keys:

    result.map { |r| r.attributes.symbolize_keys }
    
    0 讨论(0)
提交回复
热议问题