small extension: Make a hash of queried data(ActiveRecord::Relation)

Make a hash of queried data(ActiveRecord::Relation) which user can specify key

and value of the hash for some situations.

Example:

Before you do it like this

authors = Author.where(name: ‘Hank Moody’)

authors_hash = {}

authors.each do |author|

authors_hash.store(author.id, author.desc)

end

Now you do this

authors = Author.where(name: ‘Hank Moody’)

authors_hash = authors.as_hash(:id, :desc)

def as_hash(key, value, &block) k = key.to_s v = value.to_s hash = {} self.each do |item| hash.store(item[k], item[v]) yield item if block_given? end hash end

is it helpful?

Hello Yan Shi,

there’s already a method called slice. http://apidock.com/rails/Hash/slice

So you could do something like this:

authors = Author.where(name: ‘Hank Moody’) authors.attributes.slice(“id”, “desc”) # consider that AR attributes hash doesn’t have symbolized keys

Another way is to use the pluck method http://apidock.com/rails/ActiveRecord/Calculations/pluck

Author.where(name: ‘Hank Moody’).pluck(:id, :desc)

Hope that helps.

Cheers, Z