Use pluck instead of collect in ruby on rails.
I have seen lot of people use collect in ruby on rails. For example:
User.first.gifts.collect(&:id)# Bad smell.
Use pluck in case you just want to get id ie:
User.first.gifts.pluck(:id)
Explanation
‘pluck’ is on the DB level. It will only query the particular field. See this.
When you do:
User.first.gifts.collect(&:id)
You have objects with all fields loaded and you simply get the ‘id’ thanks to the method based on Enumerable.
So:
- if you only need the ‘id’, use ‘pluck’
- if you need all fields, use ‘collect’
- if you need some fields, use ‘select’ and ‘collect’
So keep in mind when to use pluck instead of collect in ruby on rails.