【发布时间】:2015-07-02 16:02:41
【问题描述】:
我有索引操作,可以从 http://localhost:3000/api/budgets?marketplace_id=1&budget_year_id=3&vendor=pepsi&details=sugarfree 之类的 url 获取参数,并使用它们通过 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
【问题讨论】:
-
试试
@budgets = Budget.where("marketplace_id=? and budget_year_id=?",params[:marketplace_id], params[:budget_year_id]).where("vendor=? or details=?",params[:vendor],params[:details]) -
谢谢你的建议,但没用
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2