Use pluck instead of collect in ruby on rails.
I have seen lot of people use collect in ruby on rails. For example:
Use pluck in case you just want to get id ie:
Explanation
‘pluck’ is on the DB level. It will only query the particular field. See this.
When you do:
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.