假设我想在我的网站上有一个包含 Rails 3 的博客,这将是我唯一拥有的东西。我想使用 Rails 来实现它,但我不喜欢 Rails 生成的 URL。我想要这样的网址:
example.com/2012/05/10/foo
我不想要我知道该怎么做的事情(使用 to_param):
example.com/entries/2012/05/10/foo
我仍然想使用像这样的助手
new_entry_path(@entry) # -> example.com/new
entry_path(@entry) # -> example.com/2012/05/10/foo
edit_entry_path(@entry) # -> example.com/2012/05/10/foo/edit
destroy_entry_path(@entry)
form_for(@entry)
link_to(@entry.title, @entry)
等等。然后我会发表评论并希望它们也可以作为自己的资源访问,例如
example.com/2012/05/10/foo/comments/5
并且这些网址也应该可以通过普通助手获得:
edit_entry_comment_path(@entry, @comment) # -> example.com/2012/05/10/foo/comments/5/edit
或类似的东西。
那么是否有可能在没有控制器名称的情况下获取 URL 并仍然使用 url 辅助方法?只需覆盖 to_param 将始终只更改 url 中控制器名称之后的部分。获得一些示例代码真的很有帮助。