重定向 HTTP 请求,避免控制器操作问题
routes.rb 文件中进行了说明,如下所示:
#routers.rb
resources :users
namespace "users" do
resources :profiles
...
end
使用上面的代码,我可以访问以下 URL:
<my_web_site>/users/1
<my_web_site>/users/1/edit
...
# and also
<my_web_site>/users/profiles/1
<my_web_site>/users/profiles/1/edit
...
我正在使用 Ruby on Rails 3。在我的项目中,我有很多类,其中一些类在我想做的是将一些 URL 请求重定向到其他 URL,但如果在
routes.rb
文件中我重定向所有这些,某些控制器操作将无法正常工作,因为这些请求被重定向(GET、POST...)。
我该如何解决这个问题?
PS:我知道(也许)我的路由器声明是错误的,但目前我正在寻找一个简单的解决方案来解决这个问题。不过,欢迎就此事提出建议。
I am using Ruby on Rails 3. In my project I have many classes and some of those are stated in the routes.rb
file like the following:
#routers.rb
resources :users
namespace "users" do
resources :profiles
...
end
With the above code I can access the following URLs:
<my_web_site>/users/1
<my_web_site>/users/1/edit
...
# and also
<my_web_site>/users/profiles/1
<my_web_site>/users/profiles/1/edit
...
What I would like to do is to redirect some URL requests to others URL but if in the routes.rb
file I redirect all those, some controller actions will not work properly because also those requests are redirected (GET, POST, ...).
How can I solve this issue?
P.S.: I know that (maybe) my router statements are wrong, but at the moment I am looking for a easy solution too the problem. However suggestions about this matter are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,看起来您想要设置一个仅适用于给定路径和一个 HTTP 动词的重定向。这似乎就是您正在寻找的内容:
根据此路由,命中
/users/profile/1
的每个GET
请求都将被重定向到/profiles/1< /code> 而任何
POST
、PUT
或DELETE
请求都不会受到重定向。仅当请求方法计算给定值时,
:via
参数才会执行重定向。它还接受动词数组,例如,您可以重定向:via =>; [:post, :put]
如果您添加有关您需要的特定重定向的更多详细信息,我们可以创建一个更好的示例。
Ok, looks like you want to set up a redirection that will only apply for to a given path and just one HTTP verb. This seems to be what you are looking for:
Based on this routes every
GET
request hitting/users/profile/1
will be redirected to/profiles/1
while anyPOST
,PUT
orDELETE
requests won't be suffering the redirection.The
:via
param will execure the redirection only if the request method math the given value. It also accepts an array of verbs so, for example, you can redirect:via => [:post, :put]
If you add more detailed information about the specific redirections that you need we can create a better example.
查看这篇精彩的文章,它将对您有所帮助:
路由
您可以在
routes.rb
。例如:
match 'some_url/:id' => redirect_to('/path_to_redirect')
Check this great article, it will help you:
routing
you can define urls that you need to redirect to in
routes.rb
.For example:
match 'some_url/:id' => redirect_to('/path_to_redirect')