ruby on rails - Validate paramaters in Restful endpoints -
i rookie in rails restful web service , trying build service returns json dump of deals.so far app returns these deals in json format when hit http://localhost:3000/api/deals. want add 2 mandatory parameters(deal_id , title) , 2 optional parameters in uri http://localhost:3000/api/deals?deal_id=2&title=book
. best way validate these 2 mandatory parameters?in other words want query if deal_id , title parameters present. assuming deal model has fields deal_id, title, description , vendor.
here 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'} resources :deals end
to validate presence of query parameters in rails route, can use :constraints
option. so, in case, if want require presence of parameters deal_id
, title
, can changing:
resources :deals
to:
resources :deals, :constraints => lambda{ |req| !req.params[:deal_id].blank? && !req.params[:title].blank? }
then, in controller, can access 4 parameters in params
hash.
alternatively, if want provide more user friendly error messages, can validation in controller. there number of approaches. this:
def action if params[:deal_id].blank? || params[:title].blank? flash[:warning] = 'deal id , title must present' redirect_to root_path , return end #rest of code goes here end
Comments
Post a Comment