Pluck in ROR is used to get an array of particular attributes based on the particular conditions from the 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.
The standard format of using the 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 an array of values of an 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 a useful method in ruby to improving the performance of your app.
Pluck returns the array and breaks the ActiveRecord query method chain so be careful when you want to query on the result.
Pluck can be used in various ways to improve our code quality as well as the speed of the app, some of them are shown below
When you want an 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]