小编Nat*_*man的帖子

使用scope在ActiveRecord中的多个DateTime范围内返回结果

我有一个Session:created_at日期和:start_time日期的模型,都存储在数据库中:time.我目前正在一个巨大的表上吐出一堆结果,并允许用户使用范围过滤单个日期和可选时间范围的结果,如下所示:

class Session < ActiveRecord::Base
  ...

  scope :filter_by_date, lambda { |date|
    date = date.split(",")[0]
    where(:created_at =>
      DateTime.strptime(date, '%m/%d/%Y')..DateTime.strptime(date, '%m/%d/%Y').end_of_day
    )
  }
  scope :filter_by_time, lambda { |date, time|
    to = time[:to]
    from = time[:from]
    where(:start_time =>
      DateTime.strptime("#{date} #{from[:digits]} #{from[:meridian]}", '%m/%d/%Y %r')..
      DateTime.strptime("#{date} #{to[:digits]} #{to[:meridian]}", '%m/%d/%Y %r')
    )
  }

end
Run Code Online (Sandbox Code Playgroud)

控制器看起来或多或少像这样:

class SessionController < ApplicationController

  def index
    if params.include?(:date) ||
       params.include?(:time) &&
     ( params[:time][:from][:digits].present? && params[:time][:to][:digits].present? )

      i = Session.scoped
      i = i.filter_by_date(params[:date]) unless …
Run Code Online (Sandbox Code Playgroud)

ruby activerecord datetime ruby-on-rails scopes

5
推荐指数
1
解决办法
1334
查看次数

标签 统计

activerecord ×1

datetime ×1

ruby ×1

ruby-on-rails ×1

scopes ×1