使用带有可选参数的 Rails where 方法查询数据库

Query the database with Rails where method with optional parameters

我有索引操作,它从 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

只有在存在可选参数的情况下,您才可以向原始查询添加额外的 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]