0

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?

poseid
  • 6,986
  • 10
  • 48
  • 78
  • Hmm.. sorry, this question was poorly formulated. My problem is that if @post is not found, \@comments will be empty, but response (200 OK). However, I would need 404 (not found), if \@post is empty. How to share that action in the controller? – poseid Feb 12 '13 at 09:56
  • 1
    In the code I gave you, I was thinking that if \@post is not found, then you'll have every comments from every posts in \@comments, not that it would be empty... But you can raise a 404 in this case if you want, check this: http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails – siekfried Feb 12 '13 at 10:21

3 Answers3

5

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
siekfried
  • 2,964
  • 1
  • 21
  • 36
1

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...
gabrielhilal
  • 10,660
  • 6
  • 54
  • 81
  • thanks. So, I understand the routes parts I think, but I am not sure about this: "in your controller, make sure you always find the post before dealing with the comments", meaning, if @post.present?; @post.comments; else; Comment.all; end ? I am just not sure if I'd better return a [] for comments when @post is nil. Hmm.. does it make sense? thanks! – poseid Feb 12 '13 at 09:41
  • one post has many comments, so url for creating and editing must have the full path `/posts/1/comments`, otherwise a comment will not be linked to the post. For this reason you must find the post that will receive a comment: `@post = Post.find(params[:post_id])` – gabrielhilal Feb 12 '13 at 09:48
0

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
sjain
  • 23,126
  • 28
  • 107
  • 185