How can I get the old attachments in ActionText before the new ones are saved? (SOLVED)

How can I get the old attachments and compare them to the newly sent ones in ActionText and Trix? The around_save callback isn’t helping. Both the old and the new attachments are the same.

class Entry
  has_rich_text :body
  around_save :create_backlinks
  
  def entry_mentions
    body.body.attachments.select { |attachment| attachment.attachable.class == Entry }.map(&:attachable).uniq
  end
  
  def create_backlinks
    old_mentions = entry_mentions
    yield
    new_mentions = entry_mentions # Results in the same as the old_mentions that is the newly sent attachments

    binding.irb
  end
end

SOLVED

class Entry < ApplicationRecord
  include ActionText::Attachable

  has_rich_text :body

  before_save :save_old_mentions
  after_save :create_backlinks

  def entry_mentions
    body.body.attachments.select { |attachment| attachment.attachable.class == Entry }.map(&:attachable).uniq
  end

  def entry_mentions_was
    @entry_mentions_was
  end

  def save_old_mentions
    @entry_mentions_was ||= body.body_was.attachments.select { |attachment| attachment.attachable.class == Entry }.map(&:attachable).uniq
  end

  def create_backlinks
    old_mentions = entry_mentions_was
    new_mentions = entry_mentions

    binding.irb
  end
end
1 Like