2017-07-21 82 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對這個你的解釋話題。實現它的方式現在看起來更加清晰。我仍然有一些錯誤,但我可以自己解決這個問題。再次感謝你對你的東西的繼續 –