我有索引操作,从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])
。我的问题是如何查询可选参数,因为它们可能并不总是存在?这是索引动作
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 :(得分: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]