How to Use Pluck in Ruby on Rails

How to Use Pluck in Ruby on Rails

07 Dec 2016
0 Comments
How to Use Pluck in Ruby on Rails

Why Use Pluck in Ruby on Rails:

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

pluck(*column_names)

 

Using Pluck:

  1. You can select one or more attributes without loading a bunch of records just to grab the attributes you want.

  2. You will get an array of values of an attribute which we pass to it.

  3. Pluck also replace select and map while querying.

  4. You can avoid extra loops to get ids from the collection of ActiveRecord while using the pluck method.

  5. Pluck is a useful method in ruby to improving the performance of your app.

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

eg. Category.pluck(:id)

# => [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

eg. Category.uniq.pluck(:name)

# => ['home', 'apartment', 'hotel']

You can use pluck in query itself

eg. categories = Category.where(name: “home”)

Service.where(category_id: categories.pluck(:id))

# => [1, 2, 3, 4, 5]




Leave a comment: