Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pluck in a selected object

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?

like image 446
HashRocket Avatar asked Oct 23 '25 09:10

HashRocket


1 Answers

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

like image 150
aBadAssCowboy Avatar answered Oct 26 '25 08:10

aBadAssCowboy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!