How to convert ActiveRecord results into an array of hashes

后端 未结 3 2081
醉梦人生
醉梦人生 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.

提交回复
热议问题