Listing all of a nested Resources

I’ll use the example on the Rails blog.

map.resources :posts do |posts|
posts.resources :comments, :trackbacks
end

Now comments are at /posts/:post_id/comments.

Okay but what if I want to list all the comments for all the posts. It
should be at /comments, but that isn’t map that way. Can I map comments
twice?

Josh P. wrote:

I’ll use the example on the Rails blog.

map.resources :posts do |posts|
posts.resources :comments, :trackbacks
end

Now comments are at /posts/:post_id/comments.

Okay but what if I want to list all the comments for all the posts. It
should be at /comments, but that isn’t map that way. Can I map comments
twice?

As I understand it (meaning untested by me), that route will generate
two valid comment collection urls

  1. /posts/:post_id/comments
  2. /comments

So I think if you call comments_url and leave out the :post_id, it will
give you ‘/comments’. Then in your controller you can have a switch
like:

def index
if params[:post_id]
Comment.find(:all, :conditions => {:post_id => params[:post_id]})
else
Comment.find(:all)
end
end

Alex W. wrote:

As I understand it (meaning untested by me), that route will generate
two valid comment collection urls

  1. /posts/:post_id/comments
  2. /comments

Tested! Thats awesome.

/comments/1 Doesn’t work.

You get Unknown action, No action responded to 1.

Josh,

Yes, in that case you can simply add another route:

map.connect ‘comments/’, :controller => ‘comments’

Hope this helps,
Zack

On 8/3/06, Josh P. [email protected] wrote:

twice?
I think you could just do
map.resources :comments

in addition to what you have.

Josh P. wrote:

/comments/1 Doesn’t work.

You get Unknown action, No action responded to 1.

I’m going to avoid this approach because it creates another action that
does the same thing as another. Not DRY.