Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to convert a query result hash

I am currently struggling with something which should be pretty straightforward in Rails.

I would like to issue one ActiveRecord query and fetch model objects from the database and subsequently store those in a hash for later lookup.

I have done some research but haven't found the optimal way to accomplish this, so would appreciate some help. My intention is to reduce the number of sql queries using lookup hashes in loop structures.

In the pseudo code below, I am fetching status codes from an sms gateway and compare those with an ActiveRecord table will all status-code descriptions.

#Status_codes in array format
status_codes = StatusCode.all

status_codes_hash = status_codes.to_array????

#Fetch delivery-status from sms gateway
response = HTTParty.get(myUrl)

response.each do |status|
if status_codes_hash[status.code]
    #Do stuff
end
end 
like image 905
Michel Kenneth Hansen Avatar asked Oct 31 '25 10:10

Michel Kenneth Hansen


1 Answers

You convert a model instance to hash via the attributes method:

StatusCode.all.map(&:attributes)
#=> [{ id: 1, code: 404, ...}, { id: 2, code: 405, ...}, ...]
like image 115
mdesantis Avatar answered Nov 03 '25 10:11

mdesantis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!