Question

In a Rails 4 app using Arel, how would I construct the following part of a WHERE clause?:

stopped_at < DATE_ADD(DATE(started_at), INTERVAL 1 DAY)

I have the following already:

started_at_date = Arel::Nodes::NamedFunction.new('DATE', [arel_table[:started_at]])
next_day = Arel::Nodes::NamedFunction.new('DATE_ADD',
                                          [started_at_date, 'INTERVAL 1 DAY'])
conditions = arel_table[:stopped_at].lt(next_day)

The problem is that INTERVAL 1 DAY gets quoted:

>> conditions.to_sql
=> "`my_table`.`stopped_at` < DATE_ADD(DATE(`my_table`.`started_at`), 'INTERVAL 1 DAY')"

MySQL does not like it being quoted, so I need to tell Arel not to quote it. How do I do this?

Was it helpful?

Solution

SqlLiteral was what I needed:

started_at_date = Arel::Nodes::NamedFunction.new('DATE', [arel_table[:started_at]])
one_day = Arel::Nodes::SqlLiteral.new('INTERVAL 1 DAY')
next_day = Arel::Nodes::NamedFunction.new('DATE_ADD',
                                          [started_at_date, one_day])
conditions = arel_table[:stopped_at].lt(next_day)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top