0

Using this as an example contexted: Post has_many comments Comment belongs_to post

I have a route that looks like:

resources :posts do
  resources :comments
end

How do i create a route that exposes comments#index?

An example use case would be... I want to list ALL comments in the system on a page. Essentially using the comments resource as if it's not nested when a user hits /comments

thank you!

Mario Zigliotto
  • 8,315
  • 7
  • 52
  • 71

1 Answers1

0

Try this.

resources :posts do
  resources :comments, :except => :index
end
match 'comments' => 'comments#index', :as => :comments

That said, I usually look to avoid routes like this because I like a tidy RESTful routes file, but sometimes it can't be helped.

Second option:

resources :posts do
  resources :comments, :except => :index
  get :comments, :on => :collection
end

In the second option, you'd want to remove the index action from the comments controller and create a comments action in your posts controller.

Preacher
  • 2,410
  • 1
  • 19
  • 29
  • Ah yes, i came up with this exact solution BUT i wasn't sure if it was right. I feel like the recommendation is normally go 100% restful but pulling out that ONE url is not. – Mario Zigliotto Jul 26 '11 at 18:46
  • I posted an alternative that's more RESTful, but I'm not sure if it's at all superior. – Preacher Jul 26 '11 at 19:09