如何将activerecord结果转换为散列数组

作为查找操作的结果,我有一个活动的logging结果

tasks_records = TaskStoreStatus.find(:all,:select => "task_id, store_name, store_region", :conditions => ["task_status = ? and store_id= ?","f" ,store_id]) 

现在我想将这个结果转换成如下所示的散列数组

 [0] -> { :task_d => 10, :store_name=> "Koramanagala", :store_region=> "India" } [1] -> { :task_d => 10, :store_name=> "Koramanagala", :store_region=> "India" } [2] -> { :task_d => 10, :store_name=> "Koramanagala", :store_region=> "India" } 

因此,我将能够遍历数组并向散列中添加更多元素,然后将结果转换为JSON以用于我的API响应!

as_json

你应该使用as_json方法将ActiveRecord对象转换成Ruby Hashes,尽pipe它的名字

 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

你也可以使用serializable_hash将任何ActiveRecord对象转换为Hash,并且可以使用to_a将任何ActiveRecord结果转换为Array,例如:

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

如果你想在v2.3之前有一个丑陋的Rails解决scheme

 JSON.parse(tasks_records.to_json) # please don't do it 

也许?

 result.map(&:attributes) 

如果你需要符号键:

 result.map { |r| r.attributes.symbolize_keys } 

回答上面的Dom的评论:如何在序列化中包含types名称?

使用to_json或as_json方法,只需在模型中包含以下片段来覆盖默认行为:

 def as_json super.as_json {methods: [:type]} end def type self.model_name.name end 

对于当前的ActiveRecord(4.2.4+), Result对象有一个方法to_hash ,它返回散列数组。 然后你可以映射它并转换为符号化的哈希值:

 # 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"}, ... ] 

有关更多信息,请参阅ActiveRecord :: Result文档 。