LarrySellers
LarrySellers

Reputation: 60

Arel query where a value is between two columns

I'd like to write a query in ActiveRecord/Arel (without hard-coding the SQL) testing that a date is between two columns: e.g. WHERE input_date BETWEEN some_table.column_1 AND some_table.column_2. I've tried the following:

between_query = Arel::Nodes::Between.new(
  Time.zone.now,
  Arel::Nodes::And.new(
    [
      arel_table[:column_1],
      arel_table[:column_2]
    ]
  )
)
where(between_query)

but I get the error Arel::Visitors::UnsupportedVisitError: Unsupported argument type: Time. Construct an Arel node instead.

Upvotes: 0

Views: 2425

Answers (2)

andrew21
andrew21

Reputation: 640

You need to replace the Time.zone.now with some sort of SQL node. If you just trying to see if the current time is between two columns, this should work:

between_query = Arel::Nodes::Between.new(
  Arel.sql('current_date'),
  Arel::Nodes::And.new(
    [
      arel_table[:column_1],
      arel_table[:column_2]
    ]
  )
)
where(between_query)

otherwise, if you are trying to pass in a variable time, instead of Arel.sql('current_date'), replace it with Arel::Nodes::Quoted.new(Time.zone.now.to_s(:db))

Upvotes: 0

Pavel Mikhailyuk
Pavel Mikhailyuk

Reputation: 2877

You can try to Construct an Arel node instead:

between_query = Arel::Nodes::Between.new(
  Arel::Nodes::Quoted.new(Time.zone.now),
  Arel::Nodes::And.new(
    [
      arel_table[:column_1],
      arel_table[:column_2]
    ]
  )
)
where(between_query)

Upvotes: 3

Related Questions