Posted over 6 years ago. Visible to the public.

ActiveRecord.select

Active Record's select method allows you to make use of the power of MySQL select statements. On the one hand it allows you to select specific fields.

Copy
Post.select("content")

results in the following query:

Copy
"SELECT content FROM `posts`"

This means that your models will be initialized with only the content attribute and you will not be able to access any other attribute. In fact trying so would raise an ActiveRecord::MissingAttributeError error.

Copy
Post.select("content").first.title # => ActiveRecord::MissingAttributeError

The only exception from this is the id attribute which returns nil when you try to access it and did not select it.

One thing to be aware of is that when you use the select method, the resulting models are read only and trying to save them will raise an exception!

On the other hand the select method allows you to include additional data in your models such as the results of MySQL functions. Those function resulst then are accessible like any other attribute of your model. Lets assume posts have many comments and we execute the following:

Copy
Post.select("posts.*, MAX(comments.created_at) AS latest_comment_at").joins(:comments).group("posts.id")

Here we included the date of the latest comment of each post using the MySQL MAX function combined with the GROUP BY clause, and thus can access it through a model by saying:

Copy
post_model.latest_comment_at

Note that we could use this new attribute in the query as well and do something like ordering the posts by the dates of their last comments.

Copy
Post.select("posts.*, MAX(comments.created_at) AS latest_comment_at").joins(:comments).group("posts.id").order("latest_comment_at DESC")

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Andreas Robecke
Last edit:
over 3 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Andreas Robecke to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more