I am trying to write a rather complicated query using baby_squeel. The query requires the use of the coalesce
SQL function. coalesce
is used as an example a couple of times on the baby_squeel home page but when I try to use it in a query I get a no method error.
Example below:
result = Table.selecting { |t| [t.col1,
((coalesce(t.col2, 0) + coalesce(t.col3, 0)).sum.as('column'))] }
.where.has { |t| t.col4 == 'some condition' }
.grouping { |t| t.col1 }
I am using Rails 5 and baby_squeel 1.2. The query is called inside of a private controller function.
Why is this happening? Do I need to require
something or define the function myself using arel?
Not sure if this will help anyone, but I found what I was missing. Since I gave arity to the block I had to reference the functions I wanted to use with the airty variable in this case t
. The correct code is:
result = Table.selecting { |t| [t.col1,
((t.coalesce(t.col2, 0) + t.coalesce(t.col3, 0)).sum.as('column'))] }
.where.has { |t| t.col4 == 'some condition' }
.grouping { |t| t.col1 }