Optionally Nested Resources

Hello,

I have this model.

city has_many stores
store belongs_to city

I created resources for them and mapped them as such, using nested
resources:

map.resources :cities, :has_many => :stores

But I wanted to make the stores available independant from the city,
so I added:

map.resources :stores

And, at this point I wonder:

  • There is an algorithmic way to convert a normal resource to a nested
    one:
    1. edit config/routes.rb and add the :has_many or the block, to
      route it as nested.
    2. change all named routes to, in this case, city_stores_
      {path,url}.
    3. edit controller, normally add a before_filter to get or find
      the parent resource.
    4. edit all find and new methods from the controller to use the
      parent.childs collection,
      to build or find the proper children resources.

So, is there a simple way to achieve this double purpose controller
without having to
create a new CityStoreController?

Any, howto, tutorial, screencast, mail, forum, blog-post, would be
very appreciated!

Thanks for reading till here, and thanks A LOT for the help you can
give.


Daniel

I have this model.

city has_many stores
store belongs_to city

I created resources for them and mapped them as such, using nested
resources:

map.resources :cities, :has_many => :stores

But I wanted to make the stores available independant from the city,
so I added:
I think about nested resources as a way to scope (or protect) access
through another. In a previous framework that I used these were referred
to as “owned” objects. These “owned” objects would be ones that don’t
make sense, or have no value, apart from their “owner.”

Take “comments” for example: A comment might be related to a blog post.
The comment has no real value apart from the post. It, therefore, makes
a lot of sense to have access to the “comment” only through the related
post.

However, in cases where a resource has value on it own. For example an
employee might belong to a department, but the employee object has value
completely apart from a department. Therefore, it makes sense for an
employee object to be managed directly rather than though a department.

This later case sounds more like what you have. It would still be fine I
suppose to nest it, but I don’t think I would. I think I would use a
more direct approach for accessing the “stores” collection like simply
going through the association from city.

Don’t confuse nested resources with associations. They are not the same
thing, even though they both share the has_many and belong_to syntax.
You don’t need nested resources everywhere your model has an
association.