Ruby-on-rails 可以在 Rails 中创建这个重定向路由吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2519436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:27:33  来源:igfitidea点击:

Possible to create this redirecting route in Rails?

ruby-on-railsredirectroutes

提问by Shpigford

Is it possible to do a redirect in the routes file of a Rails app?

是否可以在 Rails 应用程序的路由文件中进行重定向?

Specifically, I'd like to forward /j/eto /javascripts/embed.js

具体来说,我想转发/j/e/javascripts/embed.js

Right now the only way I can think to do it is to create a jcontroller with an emethod that redirects to that.

现在我能想到的唯一方法是创建一个j控制器,并使用e重定向到它的方法。

采纳答案by Tony Fontenot

Assuming rails version prior to 3.

假设 Rails 版本早于 3。

You can create a new RedirectControlleror tuck a single function away in an existing controller, to do something like the following:

您可以RedirectController在现有控制器中创建新功能或将单个功能隐藏起来,以执行以下操作:

map.js_embed '/j/e',
    :controller => :redirect_controller,
    :action => :some_function,
    :path => "embed"

Then your function would do this:

那么你的函数会这样做:

def some_function
  if params[:path]
    redirect_to "/javascripts/#{params[:path]}.js"
  end
end

or something for that effect.

或达到这种效果的东西。

回答by Steven Soroka

In Rails 4 and 5: (thanks @dennis)

在 Rails 4 和 5 中:(感谢@dennis)

get '/stories', to: redirect('/posts')

In Rails 3, you can redirect inside the routes.rb file.

在 Rails 3 中,您可以在 routes.rb 文件中重定向。

match "/posts/github" => redirect("http://github.com/rails.atom")

回答by Lucas Caton

Root path

根路径

You can make the root pathredirect to an external website:

您可以将根路径重定向到外部网站:

root to: redirect('https://www.lucascaton.com.br/en')