Nested Routes Best Practices

In a scaffold generated models, I have: List has_many Items. I then
modify the routing:

map.resources :lists, :shallow => true, :has_many => :items
map.resources :items, :only => [:index] # thought was that admin may
need look at just the items.

There will be a route generated:

list_items GET /lists/:list_id/items
{:action=>“index”, :controller=>“items”}

If I enter a url " localhost:3000/lists/2/items" it will call the
index action of the items controller with :list_id in the parameters,
but the generated default will list all items.

This is a good and bad thing. My question is: If I do this type of
routing, am I supposed to add?

if params[:list_id]
do something
@items = Item.all

It’s a good thing that I can do this because I can easily get related
resources in an ajax call. Bad in that if I forget to put something
like above in the nested controller (or restrict access some other
way), the user has access to all nested resources.

Just have not seen this mentioned anywhere - but there are a lot of

Steve A.

Hi Steve A.

I cant understand why you need

map.resources :items, :only => [:index]

 since item always coexist with lists So why it treated as seperate? 

Cant you do like

map.resources :lists, :shallow => true, :has_many => :items

And then in index of items as

def index
@list_items = list.items

def list
@list = List.find(params[:list_id])


You are right. I think I just added the :only => [:index] to test the
concept. I was trying to point out that even with:

map.resources :lists, :shallow => true, :has_many => :items

The index action is called and you must handle the situation that this
only applies if :item_id is present.

In a more complex scenario, I posted a reply in the thread <http://
d04c347caccc544a> that points out that you must handle the index
action based on the circumstance.

I may want to enter a nested route at some other point than the root
(company in the example). Project managers may want to enter nested
resources from a list of their current/active projects, or the boss
may want to see all current/active projects. Learning the RoR way of
defining these requirements has been a challenge. In some cases it
provides an elegant simple solution. In others it adds things you
didn’t expect.

Steve A.