2017-07-21 48 views
1

我在发现gem will_paginate这很棒!但我正面临使用问题。我正在构建一个群组>发布>评论应用,因此在我的群组展示页面中,我展示了帖子及其评论。为了限制查询的号码,我使用的方法包括这样的:Will_paginate for includes评论

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<%[email protected]%>"> 
    <%= render @posts %> 
</div> 
<%= will_paginate @posts, renderer: BootstrapPagination::Rails %> 

而且我的职位/彦博=

<% @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(节目)来定义@comments的方法,它可以是非常有用的;)

+0

不知是否更有意义,简单地限制你的'post.comments'到最近(3):'post.comments.order(created_at:DESC).limit(3)'。然后有一个按钮,执行一个ajax请求到另一个端点,如果用户需要它们,它将呈现剩余的请求...我想这会更有效率。 – BigRon

+0

@BigRon,谢谢你的回答,我已经把这个订单放入了我的模型评论。你能展示如何看起来像ajax请求来执行该操作吗? –

+0

尝试'@posts = Post.where(GROUP_ID:@ group.id).order(upd_at:DESC).includes(:用户,{评论:用户})' – Thanh

回答

1

不是100%测试,但我认为这应该工作。你知道所有这些组件是如何工作的吗?如果没有,让我知道,我可以解释。

帖/ _post

<% @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> 

配置/ routes.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 

posts_controller.rb

# 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 

的意见/职位/ comments.js.erb

// 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(); 

文档here解释了Ajax请求使用remote: true。向下滚动到“3.1.2 link_to”部分,然后到5.1节查看控制器和js.erb视图。

+0

感谢你这么多@BigRon对这个你的解释话题。实现它的方式现在看起来更加清晰。我仍然有一些错误,但我可以自己解决这个问题。再次感谢你对你的东西的继续 –