Renaming Rails resources
May 5, 2011
On a project, I have a “Revision” resource and URL’s like
http://foobar.dev/revisions/1
Now suddenly the client wants to rename “revision” to “edition”, so all URLs should be changed to the format
http://foobar.dev/editions/1
Unless I’m missing something in the Rails docs, there is no option to change the base part of the path without renaming the resource itself. Actions can be renamed, eg. “nuevo” instead of “new”, but I don’t think the path segment for the resource name can be changed (please correct me if I’m wrong).
I guess the proper way to go would be to rename everything: The AR model, all helper calls, controllers, tests etc. Even with lots of automation, this would be a really annoying task and I’m not inclined to spend time on this right now. Who knows if the client will change his mind again?
So instead, I ended up changes the resource from
resources :revisions
to
resources :editions, :controller => "revisions", :as => "revisions"
I’m changing the name of the resource, but the :controller option makes sure the right controller is still called, and the :as option controls the generation of path helpers (so I can keep using eg. edit_revision_path).
Remember to make the same change for nested resources.
EDIT: As Rasmus and Jakob point out, the :path option sets the actual path, not a prefix. I have made some minor updates to the Rails docs to correct this (most instances were already fixed).
May 5, 2011 at 10:23 am
You are able to do the following:
resources :revisions, :path => ‘editions’
May 5, 2011 at 10:29 am
Thanks for your reply, Rasmus, see my response to Jakob.
May 5, 2011 at 10:24 am
You should be able to do
resources :revisions, :path => 'editions'May 5, 2011 at 10:28 am
I’ll admit that I haven’t tried, but the :path option is described as a prefix in the docs:
May 5, 2011 at 10:33 am
That’s a doc-bug then.
resources :revisions, :path => 'editions'gives
$ rake routes(in /Users/jakob/Projects/foo)
revisions GET /editions(.:format) {:action=>"index", :controller=>"revisions"}
… at least in Rails 3.0.5
May 5, 2011 at 10:39 am
Rails 3.0.0 – 3.0.7 works like Jakob says.
It would probably be wise though to consult the issues on the Rails Github page and on the Rails Lighthouse project to see if there’s any indication of whether this is a doc-bug or bug in the code.
May 5, 2011 at 10:28 am
Damn you, Rasmus! I knew I shouldn’t have bothered with markup
May 5, 2011 at 10:40 am
I’m so sorry.. I was just being lazy – didn’t bother with markup since it was only one short line
May 5, 2011 at 10:44 am
Thanks again both of you. I’ll probably dig into this a bit more.