Possible to create this redirecting route in Rails?

倾然丶 夕夏残阳落幕 提交于 2020-01-11 15:08:08

问题


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

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

Right now the only way I can think to do it is to create a j controller with an e method that redirects to that.


回答1:


Assuming rails version prior to 3.

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

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.




回答2:


In Rails 4 and 5: (thanks @dennis)

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

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

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



回答3:


Root path

You can make the root path redirect to an external website:

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


来源:https://stackoverflow.com/questions/2519436/possible-to-create-this-redirecting-route-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!