How to require and check url parameters in rails 3

Is there a way in your routes file to check and check the URL parameters. I am NOT talking about restful '/ controller / action /: id' options, but 'controller / action? Param1 = x & param2 = y & param3 = z '. I need to be able to check each parameter and require them.

+4
source share
2 answers

Yes, you can. For example, to verify that param1 exists and is not empty, you must do the following:

match 'c/action' => 'c#action', :constraints => lambda{ |req| !req.params[:param1].blank? } 

You can also limit these restrictions to apply them to several routes:

 scope :constraints => lambda{ |req| !req.params[:param1].blank? } do match 'controller/action1' => 'controller#action1' match 'controller/action2' => 'controller#action2' end 
+7
source

The problem with the restriction approaches posed by Pan Thomakos is that it will prevent URLs with an invalid set of parameters from accessing your codebase, and you will be able to respond appropriately to the user (the user will see the page did not find an error, I believe).

If this meets your requirement, it’s fine, but a more convenient way for the user would be to move the parameter check to the appropriate controller, where in your action method you will go through the set of parameters obtained by this action method, and if they are not enough, you would build message senseull and returned it to the user through a notification:

+2
source

Source: https://habr.com/ru/post/1343382/


All Articles