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 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
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