[英]Rails filter by date with MetaSearch
I have some records which I show in a view. 我有一些在视图中显示的记录。 They have
start_date
and end_date
. 它们具有
start_date
和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:
过期被定义为:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.