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! :)
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.
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.
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.
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")
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