New Discussion

Notifications

You’re not receiving notifications from this thread.

Deleting Comments In Nested Threads Discussion

4
General

How about taking an OO approach i.e. changing the type to DeletedComment, e.g. using STI? This eliminates the code smell of conditionals in a partial.

Chris, what if there are validations on body column?

Unless I'm overlooking something, it seems like you have some duplicate code in the video:

def comments
  Comment.where(commentable: commentable, parent_id: id)
end

def child_comments
  Comment.where(parent: self)
end

While they use slightly different where's the end result will be the same. The commentable: commentable condition is unnecessary, as there should never exist a comment that has a different commentable than its parent.

If you're using Postgres you're likely to run into an issue with this solution due to the following columns being generated when creating the schema:

    t.bigint "user_id", null: false
    t.string "commentable_type", null: false
    t.bigint "commentable_id", null: false

This means when you delete a comment you get the following error:

ERROR:  null value in column "user_id" violates not-null constraint

The workaround that I've implemented is to add a deleted column that defaults to false on the Comments table.

This means we can set deleted to true:

comment.rb

  def destroy
    update(deleted: true)
  end

_comment.html.erb

<% if comment.deleted == true %>
    <h5 class="text-semibold">[Deleted]</h5>
    <p>[deleted]</p>
<% else %>
    <h5 class="text-semibold"><%= comment.user.name %> posted:</h5>
    <%= simple_format(comment.body) %>
<% end %>

I use your approach, but if the comment has no parents, I simply delete the record. No reasons to keep it poluting the UI

Join the discussion
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.