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?
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?
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 name
s 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.
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.
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)
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.