2
User.find([1,2,3])

I want to get name only in User model. I don't want to loop in an object so I tried:

User.find([1,2,3]).pluck(:name)

But no luck. How can I do the following scenario using pluck behavior?

HashRocket
  • 778
  • 1
  • 5
  • 15

4 Answers4

8

pluck works on ActiveRecord::Relation. find returns you objects.

I assume, you want to use pluck for the reason that it would make a single SQL query and get names alone rather than fetching all of them records and looping over them like map does to get the name

In that case, you would want to use where like

User.where(id: [1,2,3]).pluck(:name)

where chained with pluck would be the optimal way for your use case.

Documentation: find, where and pluck

aBadAssCowboy
  • 2,440
  • 2
  • 23
  • 38
7

The find method return an array and pluck is not an array method:

2.1.1 :001 > User.find([1,2,3]).pluck(:name)
  User Load (3.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` IN (1, 2, 3)
NoMethodError: undefined method `pluck' for #<Array:0x0000000f22ed90>

So if you want to do it using find you may do it like this:

User.find([1,2,3]).collect(&:name)

Or

You can do it like this:

User.where(id: [1,2,3]).pluck(:name)

And if you need the difference between pluck and collect you may refer this:

What is the difference between pluck and collect in Rails?

Update for Rails 5

In rails 5 this will work:

User.find([1,2,3]).pluck(:name)

as Зелёный mentioned that the pluck method is now added to Enumerable objects.

Community
  • 1
  • 1
Deepesh
  • 6,138
  • 1
  • 24
  • 41
4

Pluck will not work in that case. So instead of using pluck:

User.find([1,2,3]).pluck(:name)

Try using map:

User.find([1,2,3]).map(&:name)
oj5th
  • 1,379
  • 10
  • 25
2

In rails 5 it should work fine. But it wont work for any older versions.

But I think using where is more suitable,

User.where(id: [1,2,3]).pluck(:name)

Because find raise ActiveRecord::RecordNotFound error if one or more records with id: [1,2,3] not found.

M. Karim
  • 932
  • 1
  • 9
  • 18