6
votes

Suppose I want to have a blog with Rails 3 on my website and it will be the only thing I have on it. I would like to use Rails to implement it but I don't like the URLs Rails produces. I would like URLs like this:

example.com/2012/05/10/foo

I don't want something like that which I know how to do (with to_param):

example.com/entries/2012/05/10/foo

I still want to use the helpers like

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)

and so on. I then will have comments and want to make them accessible as their own resources too, like

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

and those urls should also be possible to get with the normal helpers:

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

or something like that.

So is it possible to get URLs without the controller name and still use the url helper methods? Just overwriting to_param will always just change the part after the controller name in the url. It would be really helpful to get some example code.

1

1 Answers

13
votes

Your routes.rb probably has a line something like this:

resources :entries

which produces routes of the form /entries/2012/05/10/foo.


There exists a :path argument that allows you to use something besides the default name entries. For example:

resources :entries, :path => 'my-cool-path'

will produce routes of the form /my-cool-path/2012/05/10/foo.


But, if we pass an empty string to :path, we see the behavior you're looking for:

resources :entries, :path => ''

will produce routes of the form /2012/05/10/foo.