I have multiple routes routes.rb
going to the same controller and action.
post 'ruta_1' => 'controlador#general'
post 'ruta_2' => 'controlador#general'
post 'ruta_3' => 'controlador#general'
post 'ruta_4' => 'controlador#general'
post 'ruta_5' => 'controlador#general'
There must be a more elegant way to define this in the routes file.
Personally, I think that what you mention is not the way in which the routes should be defined. One possible option, where you should modify the routes, is using constraints , something like:
where paths like
ruta/1
oruta/5
would be valid andruta/0
oruta/11
invalid. Then handle at the controller level what to do in thecase
one you mention depending on the value ofparams[:opcion]
.Now, if changing the paths isn't an option and you really need to decrease the lines of code, try:
Note that for this change to be evaluated, you must restart your rails server. Besides, always consider the factor "less lines of code" vs "understanding of the code". I think that by using a loop in the routes file, it deviates a bit from the "Rails way" which could also be interpreted as code that is understandable by other programmers who get there and not just by whoever made the change.
In case you use wildcards , consider that a solution such as
post 'ruta_(*any)'
could accept anything as a valid route, includingruta_1/otra/cosa/
, therefore it would be recommended that you accompany it with constraints of what your valid values are, something like:If you put routes from 1 to 5 just as an example and in reality the constraints are more complex than that, you can always use a PORO where you define your logic to handle the constraints.
And in case you already have logic implemented that handles that validation in the controller layer, consider moving the logic and doing it this way, since checking this is the task of the router and shouldn't even reach the controller layer. It is a detail that can be seen as minor, but it helps in the separation of responsibilities and therefore a better code.