Read more

ActiveRecord.select

Andreas Robecke
June 23, 2013Software engineer

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.

Post.select("content")
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

results in the following query:

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

 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:

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:

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.

Post.select("posts.*, MAX(comments.created_at) AS latest_comment_at").joins(:comments).group("posts.id").order("latest_comment_at DESC")
Posted by Andreas Robecke to makandra dev (2013-06-23 22:40)