2

我的模型有PostsUsersComments。用户可以在/关于帖子上发表评论。每个评论都属于一个用户和一个帖子。因此,Comment 模型有一个user_id字段和一个post_id字段。

查看 aPost时,我想通过该帖子的评论进行分页。
查看 aUser时,我想对该用户的评论进行分页。
我想使用 AJAX 进行分页(通过 Kaminari gem)。

我为两者设置了嵌套路由。

在 Post 上,被点击的 URL 是http://localhost:3000/posts/{:id}/comments?page={page_number}
On the User,被点击的 URL 是http://localhost:3000/users/{:id}/comments?page={page_number}

两个 URL 都在执行 Comments 控制器的 index 操作。

我的问题是:在index操作中,我如何确定{:id}提供的是 auser_id还是 apost_id以便我可以检索所需的评论。

4

2 回答 2

1

检查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
于 2011-05-30T20:18:41.333 回答
0

我喜欢瑞恩贝茨的方式

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
于 2014-03-06T10:53:10.277 回答