對於我的應用程序,我有項目。我使用多態性爲這些項目的評論建立了一個名爲「新評論」的模型。我跟着這個railscast。這很好。Rails - 我如何嵌套評論 - 多態
但是現在,我想在評論之上構建評論。我試着按照這個教程(http://kconrails.com/2010/10/23/nested-comments-in-ruby-on-rails-1-models/)和(http://kconrails.com/2011/01/26/nested-comments-in-ruby-on-rails-controllers-and-views/)。我在每個評論中都提供了一個評論表單。我還調整了newcomment.rb模型,以便newcomment has_many newcomments
和routes.rb文件。
問題:現在,當我以每條評論的形式發表評論時,它將作爲評論發佈到項目中,而不是作爲對特定評論的迴應。我如何調整我的代碼,以便我可以評論評論?
newcomment.rb
class Newcomment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :commentable, polymorphic: true
has_many :newcomments, :as => :commentable
belongs_to :user
scope :newest, order("created_at desc")
validates :content, presence: true
end
newcomments_controller.rb
class NewcommentsController < ApplicationController
before_filter :load_commentable
before_filter :authenticate_user!
def create
@newcomment = @commentable.newcomments.new(params[:newcomment])
if @newcomment.save
redirect_to comments_project_path(@commentable), notice: "Comment created."
else
render :new
end
end
def destroy
if current_user.try(:admin?)
@newcomment = Newcomment.find(params[:id])
@commentable = @newcomment.commentable
@newcomment.destroy
if @newcomment.destroy
redirect_to comments_url, notice: "Comment deleted."
end
else
@newcomment = Newcomment.find(params[:id])
@commentable = @newcomment.commentable
@newcomment.destroy
if @newcomment.destroy
redirect_to comments_project_path(@commentable), notice: "Comment deleted."
end
end
end
private
def load_commentable
resource, id = request.path.split('/')[1,2]
@commentable = resource.singularize.classify.constantize.find(id)
end
end
的routes.rb
resources :projects do
resources :newcomments do
resources :newcomments
end
end
視圖/項目/ _comments.html.erb
<%= render @newcomments %>
projects_controller.rb
def comments
@commentable = @project
@newcomments = @commentable.newcomments.newest.page(params[:comments_page]).per_page(10)
@newcomment = Newcomment.new
end
視圖/ newcomments/_newcomment.html.erb
<div class="comments">
<%= link_to newcomment.user.name %></strong>
Posted <%= time_ago_in_words(newcomment.created_at) %> ago
<%= newcomment.content %>
</div>
<span class="comment">
<%= form_for [@commentable, @newcomment] do |f| %>
<div class="field">
<%= f.text_area :content, rows: 3, :class => "span8" %>
</div>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="actions">
<%= f.submit "Add Comment", :class => "btn btn-header" %>
</div>
<% end %>
<% unless newcomment.newcomments.empty? %>
<%= render @newcomments %>
<% end %>
</span>