Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5.x: How can I add a route at runtime without overwriting original routes table?

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?

like image 479
Codosapien Avatar asked Jul 24 '18 05:07

Codosapien


People also ask

What does as do in Rails routes?

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.

What is RESTful route in Rails?

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.

How can you list all routes for a Rails application?

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.


1 Answers

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
like image 100
Leo Avatar answered Oct 19 '22 10:10

Leo