Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 URL without controller name

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.

like image 464
Jeena Avatar asked Jun 29 '12 22:06

Jeena


People also ask

What is namespace in Rails routes?

In a way, namespace is a shorthand for writing a scope with all three options being set to the same value.

How do I find routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

What are RESTful routes in Rails?

Rails RESTful Design REST is an architectural style(Wikipedia) that is used in Rails by default. As a Rails developer, RESTful design helps you to create default routes by using resources keyword followed by the controller name in the the routes.rb file resources :users.


1 Answers

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.

like image 197
Matchu Avatar answered Nov 08 '22 18:11

Matchu