Search code examples
ruby-on-railsrubyactiverecordarel

Re-write ActiveRecord query in Arel


I just got started with ARel. I'm finding it difficult converting this bit of complex AR query into Arel:

    Offer.where(
      "offers.ended_at IS NULL OR offers.started_at < ? AND offers.ended_at >= ?",
      Time.zone.now, Time.zone.now
    )

I think having this in Arel will aid readability


Solution

  • This should work:

    offers = Offer.arel_table
    offers_with_nil_ended_at = offers[:ended_at].eq(nil)
    offers_within_range = offers[:started_at].lt(Time.zone.now).and(
      offers[:ended_at].gteq(Time.zone.now)
    )
    
    Offer.where(offers_with_nil_ended_at.or(offers_within_range))