Sha256: ad31296d605de90f4aa8dae1b49ac13344b0ea6d1e96ac2f46c4c40e477d6e60

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

class Occams::Cms::Fragment < ActiveRecord::Base

  self.table_name = "occams_cms_fragments"

  has_many_attached :attachments

  serialize :content

  attr_reader :files

  # -- Callbacks ---------------------------------------------------------------
  # active_storage attachment behavior changed in rails 6 - see PR#892 for details
  if Rails::VERSION::MAJOR >= 6
    before_save :remove_attachments, :add_attachments
  else
    after_save :remove_attachments, :add_attachments
  end

  # -- Relationships -----------------------------------------------------------
  belongs_to :record, polymorphic: true, touch: true

  # -- Validations -------------------------------------------------------------
  validates :identifier,
    presence:   true,
    uniqueness: { scope: :record }

  # -- Instance Methods --------------------------------------------------------

  # Temporary accessor for uploaded files. We can only attach to persisted
  # records so we are deffering it to the after_save callback.
  # Note: hijacking dirty tracking to force trigger callbacks later.
  def files=(files)
    @files = [files].flatten.compact
    content_will_change! if @files.present?
  end

  def file_ids_destroy=(ids)
    @file_ids_destroy = [ids].flatten.compact
    content_will_change! if @file_ids_destroy.present?
  end

protected

  def remove_attachments
    return unless @file_ids_destroy.present?
    attachments.where(id: @file_ids_destroy).destroy_all
  end

  def add_attachments
    return if @files.blank?

    # If we're dealing with a single file
    if tag == "file"
      @files = [@files.first]
      attachments&.purge_later
    end

    attachments.attach(@files)
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
occams-1.0.0 app/models/occams/cms/fragment.rb