Rails 4范围有条件

时间:2015-07-02 11:09:15

标签: ruby-on-rails-4 scope

我有一个日期范围之间的产品。所以我有

is_active :boolean
featured  :boolean
featured_start_date :date
featured_end_date   :date

现在我需要写一个范围,该范围应该返回给我今天所有特色产品。我不确定如何在编写范围时通过有条件的日期请协助。我现在拥有的是:

scope :featured, -> { where(is_active: true, featured: true, ) }

1 个答案:

答案 0 :(得分:1)

您需要检查当前日期是否包含在特色日期范围内。 ActiveRecord没有直接的解决方案。你有一些选择:

使用SQL片段

scope :featured, -> {
  where(is_active: true, featured: true)
  .where('featured_start_date <= ?', Date.today)
  .where('featured_end_date >= ?', Date.today)
}

使用ARel

scope :featured, -> {
  where(is_active: true, featured: true)
  .where(Product.arel_table[:featured_start_date].lteq Date.today)
  .where(Product.arel_table[:featured_end_date].gteq Date.today)
}

还有更多的可能性,但这些应该可行。