2015-04-03 74 views
1

我構建了一個Rails應用程序作爲移動應用程序的API。 我想根據GET參數獲取記錄的子集。Rails範圍過濾日期時間參數

我的模式是這樣的:

# == 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 &日期= 2015 -04-03T10:44:00.000Z' 範圍:station_id有效,但:日期範圍不起作用。 有關這方面的任何線索?

謝謝

+0

嘿你在表格上有什麼? – loloso 2016-11-24 19:27:13

回答

0

看起來像日期是給你一個完整的時間戳。這幾乎是你的查詢在做什麼:

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