Ask A Question

Notifications

You’re not receiving notifications from this thread.

Deleting Comments In Nested Threads Discussion

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.

Reply

Chris, what if there are validations on body column?

Reply

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.

Reply

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 %>
Reply

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

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.