Will_paginate包括评论

时间:2017-07-21 14:39:58

标签: ruby-on-rails ruby include will-paginate

我发现宝石will_paginate很棒!但我面临使用问题。我正在建立一个组>发布>评论应用,所以在我的群组展示页面中,我正在显示帖子及其评论。为了限制查询数量,我正在使用包含这样的方法:

Group_controller:

  def show
    @posts = @group.posts.order(upd_at: :desc).includes(:user).includes(comments: :user).paginate(page: params[:page], per_page: 10)
  end

所以我想对我的评论进行分页。你知道这样做的方法吗?

我的代码: Group_show =

<h1>Groupe <%= @group.name %></h1>
<div class="post_list<%=@group.id%>">
  <%= render @posts %>
</div>
<%= will_paginate @posts, renderer: BootstrapPagination::Rails %>

我的帖子/ _post =

<% @comments = post.comments %>
<ul id="comment_list<%=post.id%>">
  <%- if @comments.any? %>
    <%= render @comments, post: post %>
    <%= will_paginate @comments, renderer: BootstrapPagination::Rails %>
  <% end %>
</ul>

顺便说一句,如果你有一个方法直接在Groups_controller(show)中定义@comments,它可能真的很有用;)

1 个答案:

答案 0 :(得分:1)

未经100%测试,但我认为这应该有效。你知道所有这些组件是如何工作的吗?如果没有,请告诉我,我可以解释一下。

<强>文章/ _post

initializeEditor(element) {
     this.editor = $(element).summernote({ .... });
}

<强>配置/ routes.rb中

<% @comments = post.comments.order(created_at: :desc).limit(3) %>
<ul id="comment_list<%=post.id%>">
  <%- if @comments.any? %>
    <%= render @comments, post: post %>
    <%- if post.comments.offset(3).exists? # this is more efficient than count > 3 bc it quits counting after 3 %>
      <!-- the below link_to creates: href="/posts/:id/comments" ... -->
      <!-- ... and `remote: true` makes that an ajax request -->
      <li><%= link_to "more", comments_post_path(post), class: "more-comments-btn", remote: true %></li>
    <% end %>
  <% end %>

</ul>

<强> posts_controller.rb

resources :posts do
  # `member do` is explained here: http://guides.rubyonrails.org/routing.html#adding-more-restful-actions
  member do
    get :comments
  end
end

<强>视图/帖/ comments.js.erb

# GET /posts/:id/comments
def comments
  @post = Post.find(params[:id])
  @comments = @post.comments.order(created_at: :desc)
  # since you requested this url via ajax with `remote: true` rails will automatically render `posts/comments.js.erb` ...
  # ... rather than a typical html request where rails would automatically render `posts/comments.html.erb`
end

文档here解释了// some people like to use render @comments as shorthand like you did above. I'm a fan of being more explicit like the below $("#comment_list<%= @post.id %>").html("<%= escape_javascript(render partial: 'comments/comments', locals: {comments: @comments, post: @post}) %>"); // now remove the more comments button $("#comment_list<%= @post.id %>").find(".more-comments-btn").remove(); 对ajax请求的使用。向下滚动到&#34; 3.1.2 link_to&#34;然后是5.1节的控制器和js.erb视图。