squeel
squeel copied to clipboard
Allow squeel to select table.*
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?
You might have figured it already, but just in case, the idea is to use backticks instead of quotes.
select { instances.*
}
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?
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).