Rails 使用 MetaSearch 按日期过滤

发布于 2024-12-17 07:57:32 字数 228 浏览 2 评论 0原文

我有一些在视图中显示的记录。它们有 start_dateend_date。 当我访问视图时,默认情况下我希望它只显示日期未过期的记录。 过期被定义为:

  • 结束日期和开始日期<=现在,并且
  • 结束日期晚于开始日期

然后我想要一个复选框来显示所有记录,包括已过期的记录。

我该如何处理这个问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疯狂的代价 2024-12-24 07:57:32

在您的控制器操作中,您希望将其放在某处:

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])

您还可以绕过所有搜索内容,只使用如下范围:

@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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文