Question

I have some records which I show in a view. They have start_date and end_date. When I access the view, by default I want it only to show records who's dates are not expired. Expired being defined as:

  • End date and start date <= Now, and
  • End date is later than the start date

I then want to have a checkbox that shows all records including the ones that have been expired.

How do I approach this?

Was it helpful?

Solution

In your controller action, you want to have this somewhere:

params[:search] ||= {} # make sure this is instantiated

# filter to show the expired records
if params[:include_expired] # check if the checkbox is checked
  params[:search][:end_date_lte] = Date.today # end_date <= Now
  params[:search][:start_date_lte] = Date.today # end_date <= Now
end

@records = params[:include_expired] ? RecordClass.where("end_date > start_date").search(params[:search]) : RecordClass.search(params[:search])

You could also bypass all the search things and just use a scope like this:

@records = params[:include_expired] ? RecordClass.expired : RecordClass.all # or whatever logic you need

# scope in the RecordClass
scope :expired, where("end_date > start_date AND end_date <= ?", Date.today)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top