[英]Ruby / Rails - AJAX pagination of nested resources - How do I determine the parent resource?
My model has Posts
, Users
, and Comments
.我的 model 有Posts
、 Users
和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.因此,评论 model 有一个user_id
字段和一个post_id
字段。
When viewing a Post
, I want to paginate through that Post's comments.查看Post
时,我想通过该帖子的评论进行分页。
When viewing a User
, I want to paginate through that User's comments.查看User
时,我想对该用户的评论进行分页。
I want to paginate using AJAX (via the Kaminari gem).我想使用 AJAX (通过 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}
在帖子上,被击中的 URL 是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}
在用户上,被击中的 URL 是http://localhost:3000/users/{:id}/comments?page={page_number}
Both URLs are hitting the index action of the Comments controller.这两个 URL 都达到了评论 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.我的问题是:在index
操作中,我如何确定提供的{:id}
是user_id
还是post_id
以便我可以检索所需的评论。
Check for params[:user_id]
and params[:post_id]
in your Comments controller:检查您的评论 controller 中的params[:user_id]
和params[:post_id]
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.