fox fox - 17 days ago 9
Ruby Question

Rails - Check if record has been updated

I am trying to check whether a record has been updated/edited, and if it has, then it should display that is has been edited.

This is my if statement:

<% if comment.changed? %>
<p id="comment-name"><%= comment.user.name %>(edited)</p>
<% else %>
<p id="comment-name"><%= comment.user.name %></p>
<% end %>


Although it isn't working. When a comment is updated, no
(edited)
text is showing. What do I need to put in the if statement to check whether the comment record has been updated?

Answer

I don't think #changed? is doing what you think it's doing.

#changed? returns true if any attribute have unsaved changes, false otherwise.

Reference


A record is edited if it's updated_at is different than created_at ( updated_at should be greater than created_at to be more precise).

<% if comment.updated_at != comment.created_at %>
    <p id="comment-name"><%= comment.user.name %>(edited)</p>
<% else %>
    <p id="comment-name"><%= comment.user.name %></p>
<% end %>