poseid
poseid

Reputation: 7156

How to share a controller action for nested routes in Rails?

In Rails, when I need:

/comments

and

/posts/1/comments

How do I best organize CommentsController? E.g. let the routes share the index actions, or work with 2 controllers?

Upvotes: 0

Views: 1268

Answers (3)

siekfried
siekfried

Reputation: 2964

You can work with only one controller.

I would go with a before_filter to check if the post_id param is present:

class CommentsController < ApplicationController
  before_filter :find_post, only: [:index]

  def index
    if @post.present?
      ## Some stuff
    else
      ## Other stuff
    end
  end

  private

    def find_post
      @post = Post.find(params[:post_id]) unless params[:post_id].nil?
    end
end

And have in your routes (with the constraints of your choice) :

resources :posts do
  resources :comments
end
resources :comments

Upvotes: 5

sjain
sjain

Reputation: 23356

You can do almost anything you want with rails routes.

routes.rb

match 'posts/:id/comments', :controller => 'posts', :action => 'comments'}

resources :posts do

   member do
    get "comments"
   end
 end

Upvotes: 0

gabrielhilal
gabrielhilal

Reputation: 10769

I believe you want /comments only for show and index actions, right? Otherwise the post params will be lost when creating or updating a comment.

In your routes.rb you can have something like:

resources : posts do
  resources :comments
end
resources :comments, :only => [:index, :show]

In your form:

form_for([@post, @comment]) do |f| 

And in your controller, make sure you find the post before dealing with the comments (for new, edit, create and update, such as:

@post = Post.find(params[:post_id])
@comment = @post...

Upvotes: 1

Related Questions