2013-04-23 108 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 %>