在 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 中拥有它将有助于提高可读性

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

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

这应该有效:

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

最新更新