【问题标题】:Query the database with Rails where method with optional parameters使用带有可选参数的 Rails where 方法查询数据库
【发布时间】: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


【解决方案1】:

仅当存在可选参数时,您才能在原始查询中添加额外的 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]

【讨论】:

  • 查询的参数超过15个怎么办?
猜你喜欢
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 2014-10-05
  • 2020-06-10
  • 2021-03-18
  • 2021-07-15
相关资源
最近更新 更多