url 中没有控制器名称的嵌套资源
我有一个非常简单的 Rails 3 应用程序,其中包含由 Devise 运行的用户模型和 Notes 模型。现在 url 和路由看起来像这样:
# url
/users/MEMBERNAME/notes/TITLE-OF-NOTE
# routing
resources :users do
resources :notes
end
但我希望 url 看起来像这样,在这种情况下路由会是什么样子?
# url
/MEMBERNAME/TITLE-OF-NOTE
更新:
谢谢,现在我发现了一个新问题。在我的表单中,我有这样的代码:
<%= form_for([@user, @note]) do |f| %>
在我的控制器中,我像这样重定向:
format.html { redirect_to([@user, @note], :notice => 'Note was successfully created.') }
在这两种情况下,当我使用 @user、@note 时,旧的 url 仍然存在。您知道如何翻译表单和重定向以使用成员/头衔结构吗?
提前致谢!
I've got a very simple Rails 3 app with a User model run by Devise and a Notes model. Right now the url and routing looks like this:
# url
/users/MEMBERNAME/notes/TITLE-OF-NOTE
# routing
resources :users do
resources :notes
end
But I would like the urls to look like this, how would the routing look like in this case?
# url
/MEMBERNAME/TITLE-OF-NOTE
Update:
Thanks, now I discovered a new problem though. In my forms I have this code:
<%= form_for([@user, @note]) do |f| %>
and in my controller I redirect like this:
format.html { redirect_to([@user, @note], :notice => 'Note was successfully created.') }
In both those cases when I use @user, @note the old urls are still present. Do you know how to translate the form and the redirects to use the member/title structure?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在此处使用自定义路线:
希望这有帮助!
更新:
要使用新创建的命名路由:
因此,一般规则是,如果将如下所示的 active_record 对象数组传递给 #redirect_to、#url_for 或 #form_for 方法,则调用 #polymorphic_url 方法在内部,并生成标准的 RESTful 路由。
You can use a custom route here:
Hope this helps!
Update:
To use the newly created named route:
So, the general rule is if you pass an array of active_record objects like below to #redirect_to, #url_for or #form_for methods, the #polymorphic_url method is called internally, and generates the standard RESTful route.
您可以使用 Rails 3 中的工作路线助手来实现您想要的路线行为,如下所示:
请参阅我的 博客文章详细介绍了我如何得出此解决方案。
You can the routes behaviour you're after with working route helpers in Rails 3 with like the following:
See my blog post for the details on how I arrived at this solution.