If I do User.all.pluck(:email)
then it works fine.
But if I do
arr = Array.new
arr = User.all
and then
arr.pluck(:email)
this is raising following error
undefined method `pluck' for #<Array:0x007f4ff8daf3c8>
which means I cannot use pluck with arrays, so how can we get particular field value from an array of records in just one line like above. I don't want to loop through each record in an array.
pluck
is useful to do a minimalist db query.
When you have an array, just use map
:
arr.map(&:email)
Use collect
, it's an Array method:
arr.collect{|u| u.email}
pluck(:x)
is the equivalent of select(:x).map(&:x)
on an ActiveRecord
collection.
If you have an array, Array#map
and its alias Array#collect
do the same job.
If you use
User.scoped.pluck(:email)
your query will be like
SELECT users.email FROM users
So, to answer the question, you can NOT use pluck on an array, pluck is an ActiveRecord::Calculations
method, not an array one.
Converting to array this way is a memory hogger. Instead you can use:
arr = User.scoped
arr.pluck :email
or in a more easy to read:
User.scoped.pluck :email
This will make sure that actual user objects are not loaded into memory until they are required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With