Remove a comment if user does not exist Ruby on Rails -
i error undefined method 'email' nil:nilclass when try access post comment user has been deleted in db.
i wonder: how can remove comments has been created users no longer exists "on fly"?
i tried this
<%= div_for(comment) %> <% if comment.user.email.nil?%> <% comment.destroy %> <%else%> <p><%= comment.body %></p> <p class="comment-submitted-by"><%= time_ago_in_words(comment.created_at) %> ago <%= comment.user.email %></p> <%end%> but still error.
you're still getting error because you've referenced comment.user.email, , user nil. need check comment.user.nil?, or you're @ risk deleting comment because user's email missing (though maybe disallow that):
<% if comment.user.nil? %> <% comment.destroy %> cleaning on fly going finicky , cumbersome. looks want dependent: :destroy on user#comments association.
class user has_many :comments, dependent: :destroy end then when user removed, of comments too, , don't have worry @ display time.
since there existing orphaned comments, can clean them out simple sql statement:
delete comments user_id not in ( select id users ) or rails console:
comments.find_each { |c| c.destroy if c.user.nil? }
Comments
Post a Comment