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?