Search code examples
ruby-on-railsruby-on-rails-3routespaginationnested-resources

Ruby / Rails - AJAX pagination of nested resources - How do I determine the parent resource?


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.


Solution

  • 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