Allow ActiveRecord::QueryMethods#select to accept a hash

Idea is to allow #select to receive hash with aliases

For example, when we using joins on different tables and we need to prepare some specific response rely on few of them, we need to write it as:

Order.joins(:users).select("users.full_name as user_name, orders.amount as order_amount, orders.created_at as order_created_at")

I propose to add ability to use hashes instead raw sql here:

Order.joins(:users).select(users: { full_name: :user_name }, orders: { amount: :order_amount, created_at: :order_created_at }) 

We already have something similar for #where in context of using it with #joins so I think it might be helpful to improve codebases and remove raw sql from these place as well.

UPD: I created PR for this suggestion: Allow ActiveRecord::QueryMethods#select to accept a hash by alextrueman · Pull Request #45612 · rails/rails · GitHub

5 Likes

I love this feature, since I was looking for column aliasing for some time already. I’ll test this locally, usually there were some problems with preloading (joins). Also looking at the implementation, maybe there is chance to actually use Arel capabilities to build the SQL select part. I’ll check locally as well and comment on PR if I found a better way. :muscle:

1 Like

Hello and thanks for reply, it’s defiantly might be done with Arel but I wanted to avoid deep changes on it so prepared light version of preparing SQL before sending it to Arel part :sweat_smile:

I just realized I tried to contribute similar change already, but there was no interest.