Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex order statement with rails AREL: SQL Case statement

I've got this bit of code that basically tries to use a SQL case statement in the active relation order method:

relation = Foo.order("CASE WHEN foos.thing IS NOT NULL THEN 0 ELSE 1 END ASC")

and in the generated (and executed) SQL it comes up as:

(ORDER BY CASE ASC)

I've tried digging down into the source and lose the thread down in the visitor.access call. Is this a known issue? Is it user error? Is there some magical thing I have to do to make it happen? I was under the impression that it just inserted the raw SQL. There are other things we're doing with the relation, such as select, limit, offset, group, having and joins.

help! :)

like image 603
jaydel Avatar asked Oct 18 '11 16:10

jaydel


People also ask

What is Arel SQL in rails?

Arel is a powerful SQL AST manager that lets us appropriately combine selection statements for simple to very complicated queries. However, reader be cautioned – Arel is still a private API provided by Rails. Meaning that future versions of Rails could be subject to changes in Arel.

What is Arel in ActiveRecord?

Arel is an AST manager used in ActiveRecord to create SQL query. Every SQL statements are represented as ruby code in Arel. Because of this, it enable to write a complicated SQL query without using raw SQL string. But it's not recommended to use Arel in the application because it's a private API.

Why use Arel SQL?

Advantages of Arel The core advantage of Arel is that working in a Ruby abstraction of SQL allows developers to tap into language features of Ruby -- method chaining, inheritance, metaprogramming -- without sacrificing any aspect of the SQL language. If you can express something in SQL, you can do it with Arel.


1 Answers

I've had this problem too:

You can put the CASE into the SELECT and name it so you can use it in the ORDER BY.

relation = Foo.select("*, CASE WHEN foos.thing IS NOT 
  NULL THEN 0 ELSE 1 END AS foo_order").order("foo_order ASC")
like image 68
PhilT Avatar answered Sep 24 '22 10:09

PhilT