简体   繁体   English

Rails 5.x:如何在运行时添加路由而不覆盖原始路由表?

[英]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? 在绘制新表时,如何在原始路径前添加,追加或以其他方式映射?

In prod's env Rails load configuration once and not listen to changes. 在prod的env Rails加载配置一次而不是听取更改。 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. 但是,您可以将新路由保存到数据库,并在服务器启动时重新创建它们,或者在ENV变量中构建routes.rb内的路由。

But if you want to use draw and need a new route just once: 但是如果你想使用draw并且只需要一条新路线:

Rails.application.routes.disable_clear_and_finalize = true  #add this line
Rails.application.routes.draw do
  #new route
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM