Say I have a controller action that should result in a new route being added to the routes table:
def make_route
vanity_url = params[:vanity_url]
vanity_redirect = params[:vanity_redirect]
return render json: { status: 400 } unless vanity_url && vanity_redirect
Rails.application.routes.draw do
get vanity_url, to: redirect(vanity_redirect)
end
render json: { status: :ok }
end
When I trigger this action, it does add the new route but completely erases the rest of the table! How do I prepend, append or otherwise map through the original routes when drawing the new table?
The :as option creates a named path. You can then call this path in your controllers and views (e.g. redirect_to things_path ). This isn't very useful for the root path (as it already named root ), but is very useful for new routes you add.
In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.
Decoding the http request TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.
In prod's env Rails load configuration once and not listen to changes. If you want to build custom routes you must reload routes each time when the new route was added:
Rails.application.reload_routes!
Also, that does not append a new route to your route file and any server restart reset your router to default. But you can save new routes to the database and recreate them when the server starts or build your routes inside routes.rb
from ENV variables.
But if you want to use draw
and need a new route just once:
Rails.application.routes.disable_clear_and_finalize = true #add this line
Rails.application.routes.draw do
#new route
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With