简体   繁体   中英

Rails filter by date with MetaSearch

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM