【问题标题】:Rails filter by date with MetaSearchRails 使用 MetaSearch 按日期过滤
【发布时间】:2011-11-21 20:45:55
【问题描述】:

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

  • 结束日期和开始日期
  • 结束日期晚于开始日期

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

我该如何处理?

【问题讨论】:

    标签: ruby-on-rails view filter meta-search


    【解决方案1】:

    在您的控制器操作中,您希望在某处拥有它:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      相关资源
      最近更新 更多