2

My model has Posts, Users, and Comments. Users can leave Comments on/about Posts. Every Comment belongs to a User and a Post. Therefore, the Comment model has a user_id field and a post_id field.

When viewing a Post, I want to paginate through that Post's comments.
When viewing a User, I want to paginate through that User's comments.
I want to paginate using AJAX (via the Kaminari gem).

I have my nested routes set up for both.

On the Post, the URL being hit is http://localhost:3000/posts/{:id}/comments?page={page_number}
On the User, the URL being hit is http://localhost:3000/users/{:id}/comments?page={page_number}

Both URLs are hitting the index action of the Comments controller.

My question is this: inside the index action, how do I determine if the {:id} provided is a user_id or a post_id so I can retrieve the desired comments.

Zabba
  • 64,285
  • 47
  • 179
  • 207
johnnycakes
  • 2,440
  • 2
  • 28
  • 36
  • You can check it with regexp on request.env["HTTP_REFERRER"] for example. If there is users match so :id belongs to user vise versa – bor1s May 30 '11 at 18:54

2 Answers2

1

Check for params[:user_id] and params[:post_id] in your Comments controller:

if params[:user_id]
  #call came from /users/ url
elsif params[:post_id]
  #call came from /posts/ url
else
  #call came from some other url
end
Zabba
  • 64,285
  • 47
  • 179
  • 207
  • These parent resource id's are not there or this appears to not be true in Rails 4, at least in the app I have built. – SWoo Nov 07 '13 at 23:11
0

I like the Ryan Bates' way

class CommentsController
  before_action :load_commentable

  def index
    @comments = @commentable.comments.page(params[:page])
  end

  private

    def load_commentable
      klass = [Post, User].detect { |c| params["#{c.name.underscore}_id"] }
      @commentable = klass.find(params["#{klass.name.underscore}_id"])
    end
end
deivid
  • 4,808
  • 2
  • 33
  • 38