Shorthand syntax for ActiveRecord select Rails 7.1
Using the newly available select syntax in Rails 7.1 we can express a SQL select 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"
There's also some shorthand you can utilize to make it even shorter. We can still add column names as Symbols, as we've always been able to. They will reference the Model the select is being performed on.
Customer.joins(:orders).select(:name, orders: [:total])
=> SELECT "customers"."name", "orders"."total" FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id"
We removed the need to declare the customers
table as it is implied from being called on the Customer
relation.
Caveat: since declaring other columns is done via a hash, that must be provided as the last argument. You couldn't say something like .select(:id, orders: [:total], :name)
.