In day-to-day life, we see many dashboards which consist of charts and reports. To build these charts or reports quickly, we required specific data from different database tables in faster queries.
The ActiveRecord::Base#pluck
method is used to query single or multiple
attributes from the database without loading the entire record.
It returns the results as an array of attribute values.
The above code will result in the following query:
The above query returns the following output:
Before
We are not limited to querying fields from a single table, we can query multiple tables as well.
While we can use the column names as a symbol it used to only work while fetching columns from a single table, but when we wanted to join multiple tables we had to go back to the string format to mention the table names.
Before Rails 7.2, we were able to fetch specific fields with the following syntax:
The above code will result in the following query:
The above query returns the following output:
After
From Rails 7.2, We can use ActiveRecord::Base#pluck to accept hash values. So, we don’t need to use the raw version of the query anymore.
Let’s take a look at the same code after this change.
The above code will result in the following query:
The same applies to pick
, which is implemented using pluck
.
pick
is short-hand for relation.limit(1).pluck(*column_names).first
,
and is primarily useful when we have a relation
that’s already narrowed down to a single row.
The above code will result in the following query:
The above query returns the following output:
In the same way, Select and Reselect also accepts the hash values.