jeudi 2 juillet 2015

Query the database with Rails where method with optional parameters

I have index action that get parameters from url like http://localhost:3000/api/budgets?marketplace_id=1&budget_year_id=3&vendor=pepsi&details=sugarfree and use them to query the database with where method. But there are two parameters that are mandatory( marketplace_id and budget_year_id) and two more that are optional (vendor and details).For mandatory parameters i can just do Budget.where("marketplace_id=? and budget_year_id=?",params[:marketplace_id], params[:budget_year_id]) .My question is how would i query for optional parameters since they are might not always be there? Here is index action

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

Aucun commentaire:

Enregistrer un commentaire