【发布时间】:2016-04-20 18:21:47
【问题描述】:
我按照 wiki 上有关此 gem 的说明进行操作:
https://github.com/mislav/will_paginate/wiki
它非常适合我的列表控制器:/ 我能够让它们分页,但我不知道如何让它与我的 cmets 一起工作。我的 cmets 控制器没有 show 方法。
class CommentsController < ApplicationController
before_action :authenticate_user!, :except => [:show]
def create
@comment = Comment.new(params[comment_params])
@comment.listing_id = params[:listing_id]
@comment.user_id = current_user.id
@comment.body = params[:comment][:body]
if @comment.save
flash[:success] = "Comment Successful."
redirect_to listing_path(@comment.listing)
else
flash[:alert] = "Comment Failed."
end
end
def destroy
@comment = @listing.comments.find(params[:id])
@comment.destroy
flash[:success] = "Comment Removed."
redirect_to listing_path(@listing)
end
private
def comment_params
params.require(:comment).permit(:user, :body)
end
end
这是我的 ListingsController 中的 show 方法:
def show
@comment = Comment.new
@comment.listing_id = @listing_id
end
这就是我理解 cmets 的原因
这是 Listings/show.html.erb 文件中渲染 cmets 的部分:
<div class="commentblock">
<div class="text-left">
<%= render partial: 'comments/form' %>
<%= render partial: 'listings/comment', collection: @listing.comments.reverse %>
</div>
</div>
我知道 ruby 代码的第一部分实际上会呈现表单,但我不明白集合部分是如何工作的或如何工作的,或者如何将分页应用于此。
列表/评论文件如下所示:
<div class="panel panel-default">
<div class="panel-heading"><%= comment.user.username %>: <%= time_ago_in_words(comment.created_at)%> ago</div>
<div class="panel-body">
<%= comment.body %>
</div>
</div>
我已经尝试了很多东西,但我仍然不知道在我的代码中要更改的位置或内容。我进入列表/评论并尝试添加:
<%= will_paginate(comment) %> # this crashed, undefined method `total_pages' for #<Comment:0x007ff556a36468>
编辑:will_paginate wiki 说当你收到我得到的错误时传递一个分页数组,但我不知道这已经完成 >.>;它没有显示你将如何做到这一点......
编辑: http://csnipp.com/s/709这个网站说你所要做的就是创建一个文件 config/initializers/will_paginate.rb 并将这行代码放入其中:
require 'will_paginate/array'
但这并没有帮助
编辑:
如果你们需要查看更多代码,它实际上在 github 上: https://github.com/ilovemysillybanana/pastie/
我真的被这个 D 卡住了:我遵循了一个关于如何制作 cmets 的教程,但他们的没有分页。
编辑: 我修好了它!
这样做的方法是替换这一行:
<%= render partial: 'listings/comment', collection: @listing.comments.reverse %>
用这一行:
<%= render partial: 'listings/comment', collection: @list_comments = @listing.comments.paginate(:page => 1, :per_page => 5) %>
但由于某种原因,我没有得到更改评论页面的数字:/
【问题讨论】:
标签: html ruby-on-rails collections rubygems will-paginate