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

Shp*_*ord 44 redirect routes ruby-on-rails

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

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

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

Ste*_*oka 161

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

get '/stories', to: redirect('/posts')
Run Code Online (Sandbox Code Playgroud)

在Rails 4中:(感谢@dennis)

match "/posts/github" => redirect("http://github.com/rails.atom")
Run Code Online (Sandbox Code Playgroud)

  • 见[http://guides.rubyonrails.org/routing.html#redirection](http://guides.rubyonrails.org/routing.html#redirection) (7认同)
  • 谢谢!我还需要在重定向中包含一个id.对于需要它的人/:匹配中的id /可以在重定向的URL中引用为/%{id}/... (7认同)
  • 在Rails 4中,`get'/ stories',to:redirect('/ posts')`,如[RoR Guides](http://edgeguides.rubyonrails.org/routing.html#redirection)中所示.请注意,由于您在路由级别重定向,因此无需创建视图. (7认同)

Ton*_*not 7

假设3之前的rails版本.

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

map.js_embed '/j/e',
    :controller => :redirect_controller,
    :action => :some_function,
    :path => "embed"
Run Code Online (Sandbox Code Playgroud)

然后你的功能会这样做:

def some_function
  if params[:path]
    redirect_to "/javascripts/#{params[:path]}.js"
  end
end
Run Code Online (Sandbox Code Playgroud)

或者那种效果的东西.