在 Arel 中重写 ActiveRecord 查询

Re-write ActiveRecord query in Arel

我刚开始使用 ARel。我发现很难将这一点复杂的 AR 查询转换为 Arel:

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

我认为在 Arel 中加入这个将有助于提高可读性

这应该有效:

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))

我认为使用链式范围也会使其更具可读性:

# in app/models/offer.rb
scope :without_end, -> { where(ended: nil) }
scope :still_valid, -> { where('started_at < :now AND offers.ended_at >= :now', now: Time.current) }

并像这样使用:

Offer.still_valid.or(Offer.without_end)