2

I have Video and Playlist models. To boost the process of displaying a thumbnail for the Playlist - I've made a column named 'thumbnail'. I would like it to be updated anytime when playlist is updated (because there's a lot of such situations in different parts of my app), so I tried to use callback after_update:

Class Playlist < ApplicationRecord

  after_update :set_thumbnail


  def set_thumbnail
    video_thumbnail = Video.find(self.content[0]).thumbnail
    self.update(thumbnail: video_thumbnail)
  end
end

Of course I've got endless cycle.

Rails docs just list methods for skipping callbacks (e.g. decrement, decrement_counter , etc.), so I have no idea how to use them.

halfer
  • 19,824
  • 17
  • 99
  • 186
a-ta-ta
  • 109
  • 1
  • 7

2 Answers2

0

after_commit callback is more suitable here. This will be run after changes are saved to database unlike after_update which execute callbacks before actual commit to database.

after_commit :set_thumbnail, on: [:update]
Ashik Salman
  • 1,819
  • 11
  • 15
0

May be it is better to use before_save here?

Class Playlist < ApplicationRecord

  before_save :set_thumbnail, on: :update


  def set_thumbnail
    video_thumbnail = Video.find(self.content[0]).thumbnail
  end
end
Vasilisa
  • 4,604
  • 3
  • 20
  • 25
  • Unfortunately. it doesn't improve the situation: update when update when update... until 'stack level's too deep'. – a-ta-ta Mar 09 '18 at 11:56
  • @a-ta-ta, please, check my answer carefully. You don't need to use `self.update` here, just set an attribute – Vasilisa Mar 09 '18 at 14:47