I need to be able to chain an arbitrary number of sub-selects with UNION
using ActiveRelation.
I'm a little confused by the ARel implementation of this, since it seems to assume UNION
is a binary operation.
However:
( select_statement_a ) UNION ( select_statement_b ) UNION ( select_statement_c )
is valid SQL. Is this possible without doing nasty string-substitution?
Because of the way the ARel visitor was generating the unions, I kept getting SQL errors while using
Arel::Nodes::Union
. Looks like old-fashioned string interpolation was the only way to get this working.I have a Shift model, and I want to get a collection of shifts for a given date range, limited to five shifts per day. This is a class method on the Shift model:
(I am using Squeel in addition to ActiveRecord)
Having to resort to string-interpolation is annoying, but at least the user-provided parameters are being sanitized correctly. I would of course appreciate suggestions to make this cleaner.
You can do a bit better than what Adam Lassek has proposed though he is on the right track. I've just solved a similar problem trying to get a friends list from a social network model. Friends can be aquired automatically in various ways but I would like to have an ActiveRelation friendly query method that can handle further chaining. So I have
which takes advantage of Squeels subquery support. Generated SQL is
An alternative pattern where you need a variable number of components is demonstrated with a slight modification to the above code
And here is a rough guess as to the solution for the OP's exact question
I like Squeel. But don't use it. So I came to this solution (Arel 4.0.2)
There's a way to make this work using arel: