2013-04-23 111 views
0

我已经创建了一个应用程序,用户可以在其中创建项目并对这些项目发表评论。现在,我有能力让用户在每个项目页面上发表评论。Ruby on Rails - 分页评论

问题:根据我的代码,我可以使用will_paginate吗?我确实安装了宝石,如果是这样,我将如何将它集成到我的代码中?如果不是,我需要做些什么来建立分页?

comment.rb

class Comment < ActiveRecord::Base 
    attr_accessible :content, :project_id, :user_id 
    validates :content, presence: true 

    belongs_to :project 
    belongs_to :user 

    scope :newest, order("created_at desc") 
end 

comments_controller.rb

class CommentsController < ApplicationController 
    before_filter :authenticate_user! 

    def create 
    project = Project.find(params[:project_id]) 
    @comment = project.comments.create!(params[:comment]) 
    redirect_to project_path(project) 
    end 
end 

项目/ show.html.erb

 <!-- Add Comments --> 

      <% if signed_in? %> 
      <p class="comment_header">Add Comment:</p> 

      <span class="comment"> 
       <%= form_for([@project, @project.comments.build]) do |f| %> 
        <div class="field"> 
        <%= f.text_area :content, :class => "span7", :rows => "3" %> 
        </div> 

        <%= f.hidden_field :user_id, :value => current_user.id %> 

        <div class="actions"> 
        <%= f.submit "Add Comment", :class => "btn btn-header" %> 
        </div> 
       <% end %> 
      </span> 

      <% else %> 

      <p class="comment_header"><%= link_to 'Sign in', new_user_session_path %> to post comments.</p> 

      <% end %> 

      <!-- Show Comments --> 
      <p class="comment_header">Comments:</p> 

      <% if @project.comments.blank? %>  
      <p>No comments made yet for this project.</p>   
      <% else %>   
      <% @project.comments.newest.each do |comment| %> 
       <div class="comments">   
       <p><%= comment.content %></p> 
       <span>By <%= link_to comment.user.name, comment.user %> <%= time_ago_in_words(comment.created_at) %> ago</span> 
       </div> 
      <% end %>  
      <% end %> 
      <!-- end of comments section --> 

回答

0

您还没有实现will_paginate正确。 (You can read about proper implementation in the documentation here.

简而言之,您需要在控制器中使用类似@comments = @project.comments.paginate(page: params[:page])的索引操作,然后遍历@comments。然后做will_paginate @comments应该正常工作。

您不能只在查看中执行查询(will_paginate @user.comments.newest),因为与正常的ActiveRecord查询不同,paginate方法返回处理分页的特殊对象。

2

是的,你可以使用will_paginate gem是。这个宝石只是为了获得一些页码的行数,你可以指定每页元素的数量。 对于为例页面1会给你件1至30 第2页31至60 .... 后,必须实现视图

+0

我确实有宝石,并尝试实施,但没有奏效。请参阅我对以下@freemanoid的回应。 – spl 2013-04-23 08:35:59

0

您可以使用will_paginate没有任何问题。你也可以看看更灵活的kaminari

+0

我的确尝试将它整合在这里:<%= will_paginate @ user.comments.newest.each do | comment | %>,但会导致一个NoMethodError未定义的方法'total_pages'关于该行。 – spl 2013-04-23 08:35:31

0

可以调用分页方法之前重定向

在你控制器

@comments = @project.comments.pagenate(page: params[:page]||1,per_page: 20) 

,并添加以下到您模板

<%= will_paginate @comments %>