2

I have a User model which is commentable:

class User < ActiveRecord::Base
  acts_as_commentable

In the Users controller I am grabbing the comments like this:

@comments = @user.comments.recent.page(params[:notifications]).per(10)

And in the Users show view there is a partial which renders the comments:

<% @comments.each do |comment| %>
  <p><%= time_ago_in_words(comment.created_at) %> ago</p>
  <h4><%= comment.comment %></h4>
<% end %>

I'm having trouble adding a link or button in the partial to lets Users delete (preferably via an AJAX call) individual comments. I know this is basic Rails but I am completely lost here.

Further info:

class Comment < ActiveRecord::Base
  include ActsAsCommentable::Comment
  belongs_to :commentable, :polymorphic => true
  default_scope -> { order('created_at ASC') }
  belongs_to :user
end

I'd really appreciate a concise and complete answer to this.

I didn't include routes.rb because currently Comments are only created in callbacks to other User actions. There is therefore no info concerning Comments in routes.rb

John Trichereau
  • 626
  • 9
  • 22

1 Answers1

0

Ok as usual the solution was simple:

routes.rb:

resources :comments, only: :destroy

UsersController:

def show
  @comments = @user.comments.recent.page(params[:notifications]).per(10)
end

views/users/_comments.html.erb:

<% @comments.each do |comment| %>
  <span id="<%= comment.id %>">
    <p><%= time_ago_in_words(comment.created_at) %> ago</p>
    <h4>
      <%= comment.comment %>
      <%= link_to comment, method: :delete, remote: true %>
    </h4>
  </span>
<% end %>

CommentsController:

def destroy
  @user = current_user
  @comment = Comment.destroy(params[:id])
  respond_to do |format|
    format.html { redirect_to user_path(@user) }
    format.xml  { head :ok }
    format.js
  end
end

views/comments/destroy.js.erb:

$('#<%= @comment.id %>').remove();
John Trichereau
  • 626
  • 9
  • 22