2013-04-23 84 views
0

我已經創建了一個應用程序,用戶可以在其中創建項目並對這些項目發表評論。現在,我有能力讓用戶在每個項目頁面上發表評論。Ruby on Rails - 如何重新排列評論視圖?

問題1:該訂單當前顯示評論,然後選擇在此下方提交新評論。當我嘗試重新排列它以顯示在評論列表之前提交評論時,我得到了NoMethodError:未定義的方法名稱爲nil:NilClass。我需要做什麼才能使評論提交框位於當前評論之上。

問題2:現在,評論正在列在最近的底部。如何翻轉訂單,以便最近的訂單處於最佳狀態?

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

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

      <% if @project.comments.blank? %>  
      <p>No comments made yet for this project.</p>   
      <% else %>   
      <% @project.comments.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 %> 

      <!-- 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 %> 
      <!-- end of comments section --> 

回答

2

1)這並不需要什麼特別。我認爲你只是在標記(... html.erb)中犯了一個錯誤。確保你採用了整個form_for/end部分,並且不要將f/text_area移到那個之外。

2)按倒序排序(最後一條評論第一條)。在評論模型的created_at日期排序DESC。

comment.rb

scope :newest, order("created_at desc") 

show.html.erb(固定顯示此代替)

<% @project.comments.newest.each do |comment| %> 
+0

感謝。想通了。使用<%@ project.comments.newest.each do | comment | %>,現在工作 – spl 2013-04-23 08:09:48

+0

rogier,你知道我怎麼可以分頁評論嗎?這可以用嗎? <%= will_paginate @comments%>? – spl 2013-04-23 08:15:48

+0

你需要 - 爲此工作一個寶石'will_paginate'。 https://github.com/mislav/will_paginate或自己構建一些東西。 – Roger 2013-04-23 08:59:26