1

I've searched through the site on how to accomplish this and many answers point towards using the changed? method. I'm trying to notify users of an update after persisting the DB so unfortunately this won't work.

I then found the previous_changes method but this also triggers when a post is first created. The goal for is to do this only edit actions. How can this be done?

<% if @post.previous_changes %>
  <span>Updated:</span> <span><%= time_ago_in_words(@post.updated_at) %> ago</span>
<% end %>
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119

4 Answers4

0

One possible solution is to set a flag whenever the element is updated.

class Model
  after_update :flag_update    

  def updated?
    !!@updated
  end

  private

  def flag_update
    @updated = true
  end
end

Then in your code simply check @post.updated?.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Why the double `!!`s? – Carl Edwards Dec 08 '15 at 20:04
  • 1
    @CarlEdwards, when `@updated` is not defined, it returns `nil`. If you do `!!` it will return `false` for `nil`. – hattenn Dec 08 '15 at 20:06
  • I think I'm starting to understand. What's the main difference between a single `!` and a double `!!`. I thought one was enough to negate something. – Carl Edwards Dec 08 '15 at 20:07
  • @CarlEdwards It is; this coerces to an actual boolean value instead of relying on truthy/falsey. – Dave Newton Dec 08 '15 at 20:09
  • Strangely couldn't get this to work. Just to give you an idea, both methods are setup in the `Post` model. I created a new post and the `Updated At` field doesn't show up (as expected). When I do update that post nothing shows. Any ideas? – Carl Edwards Dec 09 '15 at 21:04
0

You have an updated record when

@post.previous_changes.present? && @post.previous_changes["id"].nil?
Wizard of Ogz
  • 12,543
  • 2
  • 41
  • 43
0

Sounds like a good candidate for using after_update callback and in it calling a job to send an e-mail, text message or whatever your means of notifying a user is.

Using the callback to flag the model instance basically adds a state for the model and only works once because it is set after the first update. Any subsequent updates might go unnoticed depending on what and how you want to notify your users, unless you could somehow reset the state (flag), which may be a lot more work than what it is worth.

Relying on the updated_at timestamp to be greater than the created_at suffers from the same one-time opportunity than flagging.

We used an approach where we checked what a model's changes returns (you could also use changed?) before saving it, and then sent a notification after a successful save.

Jarno Lamberg
  • 1,530
  • 12
  • 12
0

If you're able to call previous_changes, why not just add a conditional to make sure that id was not changed (as per this answer):

<% if @post.previous_changes && !@post.id_changed? %>
   ...
<% end %>
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147