Routing for a Singleton Resource on Rails 2
0
While developing your RESTful Rails application, you use ActionController::Resources, which magically generates a bunch of named routes to use in controllers and views. For example, adding the following line to your config/routes.rb (I'm using Rails 2.1),
map.resources :products
,gives you these paths: products_path, product_path(id), new_product_path and edit_product_path(id).
If your resource is a singleton one, you should simply do this:
map.resource :store
However, when you try to navigate to the edit action (/store/edit) you will get an error like this:
You have a nil object when you didn't expect it! The error occurred while evaluating nil.to_sym
from the line that says <% form_for(@store) do |f| %> in your view.
I've discovered that there is already an open ticket for this issue. The problem is that Rails still assumes a collection resource. To fix this, you need to explicitly add the path to the form_for helper:
<% form_for(@store, :url => store_path) do |f| %>
Also, you will need to do the same in your update action:
redirect_to(store_path)
Now, if you are like me, you may try to use a singular name for your controller (StoreController). Now, you should get the following error:
uninitialized constant StoresController
Who mentioned StoresController?!
Well, Rails did! As documented here, the default controller name is still taken from the plural name. To solve this, just add the controller name to your route:
map.resource :store, :controller => 'store'
Now, everything should work fine. By the way, I have found a patch that allows scaffold generator to produce singleton resources: http://dev.rubyonrails.org/ticket/8832. I haven't tried it yet; has anyone given it a try?
Written by:
Hatem Mahmoud (www.expressionlab.com)
Post a Comment
eSpace podcast Prodcast
Archive
- September 2011
- April 2011
- March 2011
- December 2010
- November 2010
- September 2010
- August 2010
- July 2010
- June 2010
- April 2010
- March 2010
- November 2009
- October 2009
- September 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- November 2008
- October 2008
- September 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- January 2008
- April 2007
- March 2007
Latest Comments
- SpectraMind Commented on Egypt Wins UK's National Outsourcing Association Award
- Rofaida Awad Commented on Go Egypt Go!
- Different Mike Commented on Only idiots change their iPhone root password!
- Mike Commented on Only idiots change their iPhone root password!
- smile Commented on Only idiots change their iPhone root password!

