1

I have an SQL query I'm trying to convert to AREL. It starts out:

SELECT COUNT(id) > 0 AS exists...

So far, I have:

Arel::Table.new(:products)[:id].count.gt(0).as(:exists)

but I get:

NoMethodError - undefined method `as' for #<Arel::Nodes::GreaterThan:0x007fc98c4c58d0>

Any ideas?

3 Answers 3

1

This should do it, gives you either 0 or 1.

Arel::Table.new(:products)[:id].count.as('exists').gt(0)

Test:

> Arel::Table.new(:products)[:id].count.as('exists').gt(0).to_sql
=> "COUNT([products].[id]) AS exists > 0"
0
0

I'm not sure this is possible: gt, eq, etc. are expressions used in the WHERE part of the query. What you're trying to do here is operate in the list of fields that is part of the SELECT, which is handled by Arel's project method. This is valid:

Arel::Table.new(:products).project(product[:id].count.as(:exists))

But it won't work if you add the condition gt(0)

This isn't fancy but it does what you need:

Arel::Table.new(:products).project(Arel.sql('COUNT(id) > 0').as('exists'))
0

Note: A lot of this is conjecture since Arel is, for all practical purposes, completely undocumented! There may be better or faster ways to do this, but from the looks of it, the stuff below should be correct.

Remember that those parts of Arel produce only AST nodes that need to be passed to a SelectManager or other entities that can deal with them.

To produce the syntactic element, you can do something like:

node = Arel::Nodes::As.new(
  Arel::Table.new(:products)[:id].count.gt(0),
  'exists'
)

which produces the SQL fragment "COUNT(`products`.`id`) > 0 AS 'exists'" that you can pass into a SelectManager's #project. You can do a bit of trickery like:

Products
.where(nil) # shortcut to get a relation
.tap do |rel|
  node = () # from above

  # Go into the SelectManager and *add* a projection.
  # If you want to *replace* the entire projection, first do:
  #   rel.arel.projections = []
  rel.arel.project(node)
end

As for actually mapping the result of the predicate back to a proper Ruby boolean depending on the database backend, I leave that as an exercise for the reader, i.e., that's how I came here looking for a way to do that properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.