Reputation: 27
I am rookie in rails restful web service and i am trying build service that returns a json dump of deals.So far my app returns these deals in json format when you hit http://localhost:3000/api/deals. Now i want to add two mandatory parameters(deal_id and title) and two optional parameters in the uri http://localhost:3000/api/deals?deal_id=2&title=book
. What is the best way to validate these two mandatory parameters?In other words I just want to do the query only if deal_id and title parameters are present. Assuming Deal model has fields deal_id, title, description and vendor.
Here is my code
Controller
module Api
class DealsController < ApplicationController
respond_to :json
def index
@deals = Deal.all
respond_with (@deals)
end
end
end
routes
namespace :api,:defaults => {format:'json'} do
resources :deals
end
Upvotes: 0
Views: 459
Reputation: 2629
To validate presence of query parameters in a Rails route, you can use the :constraints
option. So, in your case, if you want to require the presence of parameters deal_id
and title
, you can do so by changing:
resources :deals
To:
resources :deals, :constraints => lambda{ |req| !req.params[:deal_id].blank? && !req.params[:title].blank? }
Then, in your controller, you can access all four parameters in the params
hash.
Alternatively, if you want to provide more user friendly error messages, you can do validation in the controller. There are a number of approaches. I would probably do something like this:
def action
if params[:deal_id].blank? || params[:title].blank?
flash[:warning] = 'Deal ID and title must be present'
redirect_to root_path and return
end
#rest of your code goes here
end
Upvotes: 1