[英]Rails - How Do I Nest Comments - Polymorphism
对于我的应用程序,我有项目。 我已经使用多态来构建一个名为“ Newcomment”的模型,用于对这些项目的评论。 我遵循了这个轨道 。 这很好。
但是现在,我想在评论之上构建评论。 我尝试按照本教程( http://kconrails.com/2010/10/23/nested-comments-in-ruby-on-rails-1-models/ )和( http://kconrails.com/2011/01 / 26 / nested-comments-ruby-on-rails-controllers-and-views / )。 我在呈现的每个评论中都添加了一个评论表单。 我还调整了newcomment.rb模型,以便newcomment has_many newcomments
和route.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
view / projects / _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>
您只需要https://github.com/elight/acts_as_commentable_with_threading ,而不是从头开始研究即可。
你不应该有这样的路线
resources :newcomments do
resources :newcomments
end
这是难闻的气味,我们需要修复。 在我们的某些项目中,我们还使用https://github.com/elight/acts_as_commentable_with_threading ,这很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.