Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pluck email from array of users

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.

like image 248
Rahul Singh Avatar asked Feb 20 '14 07:02

Rahul Singh


4 Answers

pluck is useful to do a minimalist db query.

When you have an array, just use map:

arr.map(&:email)
like image 128
apneadiving Avatar answered Nov 12 '22 01:11

apneadiving


Use collect, it's an Array method:

arr.collect{|u| u.email}
like image 20
steakchaser Avatar answered Nov 12 '22 00:11

steakchaser


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.

like image 8
xlembouras Avatar answered Nov 12 '22 01:11

xlembouras


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.

like image 1
Akash Avatar answered Nov 12 '22 01:11

Akash