如何使用Kaminari对Rails中的has_many查询进行分页



>posts Controller 索引方法

@posts = Post.includes(:replies).all

索引.html.erb

<% @post.each do |x| %>
<%= x.content %>
<% x.replies.each do |s| %>
<%= s.content %>
<% end %>
<% end %>

我想对 x.replies 进行分页并尝试了所有内容但没有用

免责声明:

在这个答案中,我将只展示如何弹出帖子的所有回复(无分页(,因为我已经有一段时间没有使用它了。

另外,我正在使用haml格式,您可以在线将其翻译成erb格式

在帖子索引页面视图中,将其添加到帖子的每一行:

# link to remote true. will call the "replies" action in the posts controller
= link_to('Show post replies', replies_post_path(post), remote: true, data: { toggle: 'modal', target: '#post_replies_modal' })
# this should be present in the view as well, this is the base for the modal pop-up which is hidden by default, and will be shown once the link_to above is clicked.
= render partial: "posts/post_replies_modal"

app/views/posts/_post_replies_modal.html.haml

# this is the modal content. right now it only shows the title 'List of replies to the post' and the buttons to close the modal. Nothing else.
# the content will be populated by the javascript request (remote: true part of the link_to)
.modal.inmodal.fade{ "id": "post_replies_modal", "tabindex": "-1", "role": "dialog" }
.modal-dialog
.modal-content
.modal-header
%button.close{ "data-dismiss": "modal", type: "button" }
%span{ "aria-hidden": "true" } ×
%span.sr-only Close
%h4.modal-title
List of replies to the post
.modal-body
#post_replies_content
.modal-footer{ style: "margin-top: 0 !important;" }
%button.btn.btn-white{"data-dismiss" => "modal", :type => "button"} Close

确保在帖子控制器中添加"回复"routes.rb

resources :posts do
member do
get :replies
end
end

app/controllers/posts_controller.rb

# this is the part that will populate the body of the modal pop-up
# this will query the replies pertaining to the post
def replies
# paginate post_replies here
# post_replies = Post.find(params[:id]).replies
respond_to do |format|
format.js do
# render template part means it will use "app/views/posts/replies.js" since 'js' is our request format
render template: "posts/replies", locals: { post_replies: post_replies }
end
end
end

app/views/posts/replies.js.haml

# this is what is called by the 'render template' from the controller
# it just uses a partial to generate an html for the replies table
# and then inserts that table in the modal body, which is in the #post_replies_content id in our popup
- post_replies_table_partial = render(partial: 'post/replies_table', format: 'html', locals: { post_replies: post_replies })
$("#post_replies_modal #post_replies_content").html("#{escape_javascript post_replies_table_partial.html_safe}");

app/views/posts/_replies_table.html.haml

# this is the partial called from above, which generates the html code for displaying the replies table
%table.table.table-striped.table-bordered
%thead
%tr
%th Reply ID
%th Reply message
%tbody
- post_replies.each do |pr|
%tr
%td= pr.id
%td= pr.message

如果您卡在某个零件中或有任何疑问,请通知我。

最新更新