[ActiveRecord] feature request - QueryMethods method that augments the select clause.

35 views
Skip to first unread message

Max Calabrese

unread,
Nov 14, 2019, 10:50:50 AM11/14/19
to Ruby on Rails: Core
One little pet peeve of mine is that there is no way (afaik) to just add additional columns to the select clause of a query. Like for example if I'm joining and want a count or aggregate off the join table:

User.joins(:answers)
       
.select('users.*','AVG(answers.score) AS average_score')


What I would really want to do is just add this to the existing select values of the scope:

User.joins(:answers)
       
.select_also('AVG(answers.score) AS average_score')

Is this a worthwhile feature? 

Josh Brody

unread,
Nov 14, 2019, 10:54:00 AM11/14/19
to rubyonra...@googlegroups.com
I've had this too. I think I delegated it to `select_with`? Same behavior different name. I'm wondering what the most Rails-y name would be.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-core/a6c37abb-1b91-4eea-978e-5a483c2e30a7%40googlegroups.com.


--

Hello from Minneapolis  Josh Brody   (952) 239-7408  www

Andrew Kaspick

unread,
Nov 14, 2019, 11:03:25 AM11/14/19
to Ruby on Rails: Core
+1

Daniel

unread,
Nov 14, 2019, 4:49:13 PM11/14/19
to rubyonra...@googlegroups.com

I like it, but I don't think it meets the criteria for inclusion in rails because it:

 * Could easily be a gem.

 * Is not meaningfully shorter.

 * Requires the next person to read this code to know what this method does.

Max Calabrese

unread,
Nov 15, 2019, 8:43:30 AM11/15/19
to rubyonra...@googlegroups.com
Its not so much that's it's shorter. They produce very different queries. Rails by default selects all the columns explicitly instead of using *.

If eager_load is used this becomes even more of a hassle since you also have to worry about selecting the the rows on the other table.

I really feel that there should be a built in method that matches the behavior of .where which does not clobber.


Daniel Heath

unread,
Nov 15, 2019, 6:02:41 PM11/15/19
to rubyonra...@googlegroups.com
Sorry, I was being unclear there.

I think it might be sensible to convert .select(“users.*, sum(baz))” to the expanded form on the ruby side using the column cache. That way you get the functionality you want without introducing a new API.

Thanks,
Daniel Heath 

On 16 Nov 2019, at 12:43 am, Max Calabrese <max.f.c...@gmail.com> wrote:


Reply all
Reply to author
Forward
0 new messages