0

我有索引操作從url獲取參數,如http://localhost:3000/api/budgets?marketplace_id=1&budget_year_id=3&vendor=pepsi&details=sugarfree,並使用它們使用where方法查詢數據庫。但有兩個參數是強制性的(marketplace_id and budget_year_id)和另外兩個是可選的(vendor and details)。對於強制參數我可以做Budget.where("marketplace_id=? and budget_year_id=?",params[:marketplace_id], params[:budget_year_id])。我的問題是我將如何查詢可選參數,因爲它們可能並不總是在那裏?這裏是索引操作使用Rails查詢數據庫where可選參數的方法

def index 
    unless params[:marketplace_id].blank? || params[:budget_year_id].blank? 
     @budgets = Budget.where("marketplace_id=? and budget_year_id=?",params[:marketplace_id], params[:budget_year_id])# How do i add optional parameters ,vendor and/or details 
     respond_with (@budgets) 
    else 
     render :json=>{:errors =>"Marketplace_id and Budget_year_id must be present",:status=>402} 
    end 
end 
+0

嘗試'@budgets = Budget.where( 「marketplace_id =和budget_year_id =?」,則params [:marketplace_id],則params [:budget_year_id])。?其中(「供應商=或細節= ?「,params [:vendor],params [:details])' – Pavan

+0

謝謝你的建議,但這沒有奏效 – Katie

回答

2

只有當可選參數存在時,纔可以將附加的where子句添加到原始查詢中。直到您嘗試訪問查詢的結果時纔會執行該查詢。例如:

@budgets = Budget.where(marketplace_id: params[:marketplace_id], 
    budget_year_id: params[:budget_year_id]) 

@budgets = @budgets.where(vendor: params[:vendor]) if params[:vendor] 
@budgets = @budgets.where(details: params[:details]) if params[:details] 
+0

如果查詢中有超過15個參數,該怎麼辦? –