0

我正在處理我的第一個rails項目,並且無法正常運行我的查詢。我的總體目標是設置一系列範圍,以創建具有多個選項的長查詢。但是,首先,我只是想設置一個範圍,從單個模型中查詢單個列。這裏是我的模型:在控制器中使用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 

和視圖是軌道的默認索引視圖。

當我在搜索字段中輸入一個輸入時,例如「Case」,提交按鈕就起作用並將我引導到索引視圖,但列出了所有「繪圖」,而不僅僅是那些具有「案例「作爲他們的描述。非常感謝你的幫助。

這裏是適用,因爲你可以看到開發日誌文件,生成的SQL不包括添加的描述參數的部分:

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

服務器日誌應打印出從範圍生成的數據庫查詢,你可以將其粘貼在? – mbaird

+0

發送空白輸入時會發生什麼?你是否列出所有「繪圖」? – Bala

+0

是的,如果我發送任何輸入,包括空白,我會列出所有圖紙。 – sabrams

回答

2

】這個params是錯誤的。

而不是

params[:description] 

使用

params[:drawings][:description]