Rails 3 URL without controller name
Asked Answered
E

1

5

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.

Encephalograph answered 29/6, 2012 at 22:23 Comment(0)
H
13

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.

Haleakala answered 29/6, 2012 at 22:44 Comment(3)
Yeah, I'm trying to work that out myself—and not just one, but two! Maybe it's an objection to the seeming sketchiness of the solution (I can see intuition dictating that the routes would be //2012/05/10/foo with an extra preceding slash), but it definitely works and is definitely far easier and more Rails-y than reimplementing all the resourceful routes by hand.Haleakala
Yea. It was at -3 when I got here. Perhaps because the route you specified doesn't actually have the /year/month/date stuff?Erin
@jaredonline: from the phrasing of the question, I assumed that OP already year/month/day implemented within the context of resourceful routes, so the path parameter is all there's left to add :/ Meh.Haleakala

© 2022 - 2024 — McMap. All rights reserved.