How to Use Pluck in Ruby on Rails
Why Use Pluck in Ruby on Rails:
Pluck in ROR is used to get array of particular attribute based on particular condition from database. If you only require a few attributes from a table, rather than instantiating a collection of models and then running a .map over them to get the data you need, it’s much more efficient to use .pluck to pull back only the attributes you need as an array.
The benefits of using pluck are: better SQL performance and less time and memory spent in Ruby on Rails.
Standard format of using pluck method is
- You can select one or more attributes without loading a bunch of records just to grab the attributes you want.
- You will get array of values of attribute which we pass to it.
- Pluck also replace select and map while querying.
- You can avoid extra loops to get ids from the collection of ActiveRecord while using the pluck method.
- Pluck is useful method in ruby to improving performance of your app.
- Pluck returns the array and breaks the ActiveRecord query method chain so becareful when you want to query on the result.
Pluck can be use in various ways to improve our code quality as well as speed of app, some of them are shown below
When you want array of ids from a table you can use pluck
# => [1, 2, 3]
You can use pluck to get array of multiple attributes from table
eg. Service.pluck(:id, :business_id)
# => [[1, 3], [2, 5], [3, 2]]
If you want unique values of attribute in array you can use pluck as given below
# => ['home', 'apartment', 'hotel']
You can use pluck in query itself
eg. categories = Category.where(name: “home”)
# => [1, 2, 3, 4, 5]