Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails key ActiveRecord result set into hash

I have a trivial ActiveRecord query that looks like the following in my Ruby on Rails 4 application:

ps = PlayerSalary.where(gamedate: date, site_id: site.id).find_all_by_player_id(player_ids)

My question is the following. the ps set could have a couple hundred records at any given time, normally up to 300. I want to be able to be able to access a record from it when I loop over player_ids like the following:

player_ids.each do |pid|
  # retrieve record from `ps` where ps.player_id == pid
end

The fastest way to do that would be to organize the ps set up by hash where the key is the player_id. What's the best way to create that hash from ps?

like image 940
randombits Avatar asked Dec 25 '22 06:12

randombits


1 Answers

In one line:

ps.each_with_object({}) { |r, h| h[r.id] = r }

like image 74
A Fader Darkly Avatar answered Jan 08 '23 21:01

A Fader Darkly