[英]Rails kaminari pagination for child table
我有2個類: Posts
和Comments
,其中帖子has_many :comments
和comments belongs_to post
。
我的每篇文章都有一個顯示頁面,其中包含評論列表,我想對這些評論進行分頁。 使用當前的代碼,我將顯示所有頁面上所有注釋的列表。 因此,如果我有10條評論,而我希望每頁有2條評論,那么我會得到5頁,上面有10條評論。 有人可以照亮嗎?
我的代碼:
Posts controller:
def show
@post = Post.find(params[:id])
@comments = @post.comments.page(params[:page]).per(3)
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
"Show" views:
<%= paginate @comments %>
<% @post.comments.each_with_index do |comments, index| %>
<tr>
<td><%= index+1 %></td>
<td><%= comment.date %></td>
<td><%= comment.text %></td>
</tr>
<% end %>
</table>
您需要在視圖中使用分頁對象,而不是從數據庫中獲取它們:
<% @comments.each_with_index do |comments, index| %>
<tr>
<td><%= index+1 %></td>
<td><%= comment.date %></td>
<td><%= comment.text %></td>
</tr>
<% end %>
這使它們新鮮,沒有分頁:
@post.comments
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.