对于我的应用程序,我有项目。我使用多态性构建了一个名为“Newcomment”的模型,用于对这些项目进行评论。我跟着这个railscast。这很好用。
但是现在,我想在评论之上建立评论。我尝试按照本教程(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 模型,以便 newcommenthas_many newcomments
和 routes.rb 文件。
问:现在,当我以每条评论的形式发表评论时,它会作为对项目的评论发布,而不是作为对特定评论的回应。我将如何调整我的代码,以便我可以对评论进行评论?
新评论.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
路线.rb
resources :projects do
resources :newcomments do
resources :newcomments
end
end
查看/项目/_comments.html.erb
<%= render @newcomments %>
项目控制器.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>