I'm doing my best to bend my brain around arel and the relational algebra behind it, but how to represent a SELECT DISTINCT
is consistently eluding my comprehension. Can anyone explain how to arel:
SELECT DISTINCT title FROM posts;
Many thanks!
Using pure Arel (not Rails/ActiveRecord) there is a "distinct" method:
Arel::VERSION # => '3.0.2'
posts = Arel::Table.new(:posts)
posts.project(posts[:title])
posts.distinct
posts.to_sql # => 'SELECT DISTINCT "posts"."title" FROM "posts"'
Curiously, the "distinct" method is not chainable, per the other Arel methods.
The Arel way to do it is:
t = Arel::Table.new(:foo)
count_distinct = t[:field].count(true)
count_distinct.to_sql # => "COUNT(DISTINCT `foo`.`field`)"
The previous answer is the Rails way, no? Not the Arel way.
This works for arel 1.x:
posts = Table(:posts)
posts.project(Arel::Distinct.new(posts[:title]))
I'd guess there's another "more correct" way to do this via the API but I haven't figured that out yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With