Search code examples
ruby-on-railsrubyroutesnested-resources

Exposing a Specific Action of a Nested Route


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!


Solution

  • 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.