我正在开发我的第一个rails项目,但是我无法让我的查询正常工作。我的总体目标是设置一组范围,以创建一些具有多个选项的长查询。但是,首先,我只是尝试设置一个范围,从单个模型中查询单个列。这是我的模特:
class Drawing < ActiveRecord::Base
has_many :revisions
scope :by_description, lambda { |description| where(description: description) unless description.nil? }
end
以下是我的控制器的索引操作:
def index
@drawings = Drawing.by_description(params[:description]).all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @drawings }
end
end
视图是rails的默认索引视图。
当我在搜索字段中输入输入时,例如“Case”,提交按钮起作用并将我引导到索引视图,但是列出了所有“图纸”,而不是仅列出具有“案例”的图纸“作为他们的描述。非常感谢你的帮助。
以下是适用的开发日志文件部分,如您所见,正在生成的SQL不包括添加的description参数:
Started GET "/drawings?utf8=%E2%9C%93&drawings%5Bdescription%5D=Case&drawings%5Bdrawing_number%5D=&drawings%5Bitem_number%5D=&drawings%5Bpump_model%5D=&drawings%5Bframe_size%5D=&drawings%5Bpart_type%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=&drawings%5Bcreated_after%282i%29%5D=&drawings%5Bcreated_after%283i%29%5D=&commit=Search" for 127.6.43.1 at 2013-08-31 11:39:28 -0400
Processing by DrawingsController#index as HTML
Parameters: {"utf8"=>"✓", "drawings"=>{"description"=>"Case", "drawing_number"=>"", "item_number"=>"", "pump_model"=>"", "frame_size"=>"", "part_type"=>"", "created_before(1i)"=>"", "created_before(2i)"=>"", "created_before(3i)"=>"", "created_after(1i)"=>"", "created_after(2i)"=>"", "created_after(3i)"=>""}, "commit"=>"Search"}
[1m[36mDrawing Load (0.3ms)[0m [1mSELECT "drawings".* FROM "drawings" [0m
Rendered drawings/index.html.erb within layouts/application (6.0ms)
Completed 200 OK in 226ms (Views: 186.8ms | ActiveRecord: 0.3ms)
答案 0 :(得分:3)
参数是错误的。
而不是
params[:description]
使用
params[:drawings][:description]