我在查询时遇到问题。我的模型中有一个范围列表:
class Drawing < ActiveRecord::Base
has_many :revisions
scope :by_description, lambda { |description| where('description LIKE ?', "%#{description}%") unless description.nil? }
scope :by_drawing_number, lambda { |drawing_number| where('drawing_number LIKE ?', "%#{drawing_number}%") unless drawing_number.nil? }
scope :by_item_number, lambda { |item_number| where('item_number LIKE ?', "%#{item_number}%") unless item_number.nil? }
scope :by_pump_model, lambda { |pump_model| where('pump_model LIKE ?', "%#{pump_model}%") unless pump_model.nil? }
scope :by_frame_size, lambda { |frame_size| where('frame_size LIKE ?', "%#{frame_size}%") unless frame_size.nil? }
scope :by_part_type, lambda { |part_type| where('part_type LIKE ?', "%#{part_type}%") unless part_type.nil? }
scope :by_created_before, lambda { |created_before| where('created_at <= ?', created_before) unless created_before.nil? }
scope :by_created_after, lambda { |created_after| where('created_at >= ?', created_after) unless created_after.nil? }
我在控制器的索引操作中调用它们:
def index
@drawings = Drawing.by_description(params[:drawings][:description]).by_drawing_number(params[:drawings][:drawing_number]).\
by_item_number(params[:drawings][:item_number]).by_pump_model(params[:drawings][:pump_model]).by_frame_size(params[:drawings]\
[:frame_size]).by_part_type(params[:drawings][:part_type]).by_created_before(params[:drawings][:created_before]).\
by_created_after(params[:drawings][:created_after]).all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @drawings }
end
end
所有查询都有效,我可以使用它们来过滤任何给定变量的搜索,除了 by_created_before 和 by_created_after 范围。参数哈希显示已输入搜索的日期,但输出的查询不包括这两个范围。这是日志的片段:
Started GET "/drawings?utf8=%E2%9C%93&drawings%5Bdescription%5D=&drawings%5Bdrawing_number%5D=&drawings%5Bitem_number%5D=&drawings%5Bpump_model%5D=&drawings%5Bframe_size%5D
e%5D=&drawings%5Bcreated_before%281i%29%5D=&drawings%5Bcreated_before%282i%29%5D=&drawings%5Bcreated_before%283i%29%5D=&drawings%5Bcreated_after%281i%29%5D=2013&drawings%5B
%5D=5&drawings%5Bcreated_after%283i%29%5D=2&commit=Search" for 127.6.43.1 at 2013-08-31 16:49:56 -0400
Processing by DrawingsController#index as HTML
Parameters: {"utf8"=>"✓", "drawings"=>{"description"=>"", "drawing_number"=>"", "item_number"=>"", "pump_model"=>"", "frame_size"=>"", "part_type"=>"", "created_before(1i
re(2i)"=>"", "created_before(3i)"=>"", "created_after(1i)"=>"2013", "created_after(2i)"=>"5", "created_after(3i)"=>"2"}, "commit"=>"Search"}
Drawing Load (0.6ms) SELECT "drawings".* FROM "drawings" WHERE (description LIKE '%%') AND (drawing_number LIKE '%%') AND (item_number LIKE '%%') AND (pump_model LIKE '%
IKE '%%') AND (part_type LIKE '%%')
Rendered drawings/index.html.erb within layouts/application (11.4ms)
Completed 200 OK in 291ms (Views: 86.7ms | ActiveRecord: 0.6ms)
我也尝试过使用
lambda {|created_before| where(:created_at <= created_before)...}
感谢您的任何建议!