【问题标题】:Rails scope filtering datetime paramRails 范围过滤日期时间参数
【发布时间】:2015-04-03 13:10:45
【问题描述】:

我构建了一个 Rails 应用程序作为移动应用程序的 API。 我想根据 GET 参数获取记录的子集。

我的模型是这样的:

# == Schema Information
#
# Table name: inspections
#
#  id         :integer          not null, primary key
#  date       :date
#  station_id :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
class Inspection < ActiveRecord::Base
  include Filterable

  belongs_to :station
  has_many :state_checks

  scope :station_id, -> (station_id) { where station_id: station_id }
  scope :date, -> (date) { where date: DateTime.parse(date) }
end

然后我写了一个关注:

module Filterable
  extend ActiveSupport::Concern

  module ClassMethods
    def filter(filtering_params)
      results = self.where(nil)
      filtering_params.each do |key, value|
         results = results.public_send(key, value) if value.present?
      end
      results
    end
  end
end

现在,当我执行 GET '/inspections.json?station_id=1&date=2015-04-03T10:44:00.000Z' 范围 :station_id 有效,但 :date 范围无效。 有什么线索吗?

谢谢

【问题讨论】:

  • 嘿,你的表格上有什么?

标签: ruby-on-rails datetime get params


【解决方案1】:

看起来 date 为您提供了完整的时间戳。这几乎就是您的查询正在做的事情:

date_1 = DateTime.parse('2015-04-03T10:01:00.000Z')
-> 'Fri, 03 Apr 2015 10:01:00 +0000'
date_2 = DateTime.parse('2015-04-03T10:11:00.000Z')
-> 'Fri, 03 Apr 2015 10:11:00 +0000'
date_1 == date_2
-> false

您的查询正在检查直到第二个的相等性。看起来你需要更多这样的东西:ActiveRecord Find By Year, Day or Month on a Date field

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2017-04-23
    • 2015-05-23
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多