squeel icon indicating copy to clipboard operation
squeel copied to clipboard

Allow squeel to select table.*

Open lowjoel opened this issue 9 years ago • 3 comments

I'm trying to achieve:

SELECT instances.*,
    count("instance_users"."id") AS user_count,
    count("courses"."id") AS course_count
FROM "instances"
    LEFT OUTER JOIN "instance_users" ON "instance_users"."instance_id" = "instances"."id"
    LEFT OUTER JOIN "courses" ON "courses"."instance_id" = "instances"."id"
    GROUP BY "instances"."id"

The best I can get so far is:

Instance.joins { instance_users.outer }.joins { courses.outer }.
          select { 'instances.*' }.
          select { count(instance_users.id).as(user_count) }.
          select { count(courses.id).as(course_count) }.
          group { instances.id }

I still need to specify the instances.* string in the second line. Is there any way in the DSL to select all columns?

lowjoel avatar Jun 10 '15 07:06 lowjoel

You might have figured it already, but just in case, the idea is to use backticks instead of quotes.

select { instances.* }

octavpo avatar Sep 07 '15 07:09 octavpo

Normal quotes work, but I think it might be more expressive if this was part of the Squeel DSL.

I'm not sure if backquotes are treated differently?

lowjoel avatar Sep 30 '15 06:09 lowjoel

I keep getting back here, and I finally found what seems to me the cleanest solution:

User.select(User.arel_table[Arel.star])

Or in a scope:

scope :with_custom, -> { select(arel_table[Arel.star]).select{CONCAT(name, ':').as(custom)} }

Or maybe we should just add this to ActiveRecord::Base:

scope :select_all, -> { select(arel_table[Arel.star])) }
scope :with_custom, -> { select_all.select{CONCAT(name, ':').as(custom)} }

This is not a problem with squeel, but with ActiveRecord (that doesn't allow you to add select columns vs replace entirely).

odedniv avatar Apr 06 '16 07:04 odedniv