Today I Learned

hashrocket A Hashrocket project

Hash syntax for ActiveRecord select in Rails 7.1

Previously, when writing an ActiveRecord select and wanted to add columns from anything outside of the model you originated from, you'd have to provide a SQL fragment string like so:

Customer.joins(:orders).select("customers.name, orders.total")

=> SELECT customers.name, orders.total FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id"

Notice above how we declare columns from the customers table and the orders table.

As of Rails 7.1, you can now stay in the ActiveRecord DSL and provide hash key/values. The query example above can directly be expressed as:

Customer.joins(:orders).select(customers: [:name], orders: [:total])

=> SELECT "customers"."name", "orders"."total" FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id"

You provide the table names as keys and the column names you want to select as Symbols in an Array.

Also, notice that the selected columns in the query are appropriately quoted vs the SQL fragment above.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.