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
On Wednesday, December 18, 2013 11:45:00 AM UTC+1, yan shi wrote:
>
> 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?
>
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.