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.
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}
http://localhost:3000/users/{:id}/comments?page={page_number}
Both URLs are hitting the index action of the Comments cont开发者_如何学Pythonroller.
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.
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
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
精彩评论