mercredi 11 octobre 2017

Get hash of id => property in Rails

I have an ActiveRecord model like this:

class Person < ActiveRecord::Base
  attr_accessible :name
end

and need to get a hash mapping persons ids to their names. Now, the obvious way would be

Person.all.collect { |p| [p.id, p.name] }.to_h

However, I don't need to instantiate every Person, I just need the hash. In Rails 4, I can .pluck(:id, :name) instead of collect, however in 3.x, pluck takes only one argument. However I found this workaround to get what I want without loading the models:

Person.all.group(:id).minimum(:name)

Question: will I burn in hell? Also, is there a more elegant way to do this, and are there any drawbacks of this hacky approach that I may not be aware of? Thanks!

Aucun commentaire:

Enregistrer un commentaire