我有索引操作從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
嘗試'@budgets = Budget.where( 「marketplace_id =和budget_year_id =?」,則params [:marketplace_id],則params [:budget_year_id])。?其中(「供應商=或細節= ?「,params [:vendor],params [:details])' – Pavan
謝謝你的建議,但這沒有奏效 – Katie