Rails 3没有控制器名称的URL

Jee*_*ena 6 routes ruby-on-rails urlhelper

假设我想在我的网站上建立一个带有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)
Run Code Online (Sandbox Code Playgroud)

等等.然后,我会发表评论,并希望将它们作为自己的资源进行访问,例如

example.com/2012/05/10/foo/comments/5

那些网址也应该可以与普通的帮助者一起使用:

edit_entry_comment_path(@entry, @comment) # -> example.com/2012/05/10/foo/comments/5/edit
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

那么是否可以获取没有控制器名称的URL并仍然使用url帮助器方法?只需覆盖to_param将始终只更改url中控制器名称后的部分.获得一些示例代码真的很有帮助.

Mat*_*chu 13

routes.rb可能有这样的行:

resources :entries
Run Code Online (Sandbox Code Playgroud)

产生形式的路线/entries/2012/05/10/foo.


存在一个:path允许您使用默认名称之外的参数的参数entries.例如:

resources :entries, :path => 'my-cool-path'
Run Code Online (Sandbox Code Playgroud)

将产生形式的路线/my-cool-path/2012/05/10/foo.


但是,如果我们传递一个空字符串:path,我们会看到您正在寻找的行为:

resources :entries, :path => ''
Run Code Online (Sandbox Code Playgroud)

将产生形式的路线/2012/05/10/foo.

  • @jaredonline:从问题的措辞来看,我假设OP已经在资源丰富的路由的上下文中实现了年/月/日,所以路径参数是剩下要添加的:/ Meh. (2认同)