Rails - How Do I Nest Comments - Polymorphism -
for application, have projects. have used polymorphism build model called "newcomment" comments made on these projects. followed railscast. works great.
but now, want build comments on top of comments. tried following tutorial (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/). put form comments in each comment render. adjusted newcomment.rb model, newcomment has_many newcomments
, routes.rb file.
question: right now, when make comment in form of each comment, posts comment project , not response specific comment. how adjust code can have comments comments?
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 resources :newcomments 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
view/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] |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>
all need, instead of working on scrap, is: https://github.com/elight/acts_as_commentable_with_threading
Comments
Post a Comment