Programing

ActiveRecord 결과를 해시 배열로 변환하는 방법

lottogame 2020. 8. 21. 08:21
반응형

ActiveRecord 결과를 해시 배열로 변환하는 방법


찾기 작업의 ActiveRecord 결과가 있습니다.

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" }

배열을 반복하고 해시에 더 많은 요소를 추가하고 나중에 JSONAPI 응답 위해 결과를로 변환 할 수 있습니다 . 어떻게 할 수 있습니까?


as_json

as_json이름에도 불구하고 ActiveRecord 객체를 Ruby Hashes로 변환 하는 메소드를 사용해야합니다.

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

또한를 사용하여 모든 ActiveRecord 객체를 해시로 serializable_hash변환 할 수 있으며를 사용하여 모든 ActiveRecord 결과를 배열로 변환 할 수 있습니다 to_a.

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

v2.3 이전의 Rails에 대한 추악한 솔루션을 원한다면

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

아마도?

result.map(&:attributes)

기호 키가 필요한 경우 :

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

현재 ActiveRecord (4.2.4+)의 경우 해시 배열을 반환하는 개체 to_hash대한 메서드 Result있습니다. 그런 다음 그 위에 매핑하고 기호화 된 해시로 변환 할 수 있습니다.

# 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 문서를 참조하십시오 .

참고 URL : https://stackoverflow.com/questions/15427936/how-to-convert-activerecord-results-into-an-array-of-hashes

반응형