Reputation: 358
I have a product which is to be featured between a date range. So I have
is_active :boolean
featured :boolean
featured_start_date :date
featured_end_date :date
now I need to write a scope which should return to me all the featured products for today's date. I am not sure how I can pass the conditional date when writing the scope please assist. What I have right now is:
scope :featured, -> { where(is_active: true, featured: true, ) }
Upvotes: 0
Views: 524
Reputation: 54674
You need to check whether the current date is contained in the featured date range. ActiveRecord has no direct solution to this. You have some options though:
Using SQL fragments
scope :featured, -> {
where(is_active: true, featured: true)
.where('featured_start_date <= ?', Date.today)
.where('featured_end_date >= ?', Date.today)
}
Using 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)
}
There are more possibilities but these should work just fine.
Upvotes: 1