问题
I'm discovering the gem will_paginate which is great ! But I'm facing a problem of using. I'm building a group>post>comments app, so in my group show page i'm displaying posts and their comments. To limit the numbers of queries, i'm using includes method like this :
Group_controller :
def show
@posts = @group.posts.order(upd_at: :desc).includes(:user).includes(comments: :user).paginate(page: params[:page], per_page: 10)
end
So I would like to also paginate my comments. Do you know a way to do that ?
My code : Group_show =
<h1>Groupe <%= @group.name %></h1>
<div class="post_list<%=@group.id%>">
<%= render @posts %>
</div>
<%= will_paginate @posts, renderer: BootstrapPagination::Rails %>
And my posts/_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>
By the way if you have a method to define @comments directly in the Groups_controller(show), it can be really useful ;)
回答1:
Not 100% tested, but I think this should work. Do you know how all these components work? If not, let me know and I can explain.
posts/_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>
config/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
views/posts/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();
The documentation here explains the use of remote: true
for ajax requests. Scroll down to section "3.1.2 link_to" and then section 5.1 for the controller and js.erb view.
来源:https://stackoverflow.com/questions/45240450/will-paginate-for-includes-comments