Sha256: 061719ca105aa1fbd4f342271604fe951b4233dc85a6f1612f620a8f3869bf5c

Contents?: true

Size: 1.5 KB

Versions: 10

Compression:

Stored size: 1.5 KB

Contents

class Comfy::Cms::Fragment < ActiveRecord::Base

  self.table_name = "comfy_cms_fragments"

  has_many_attached :attachments

  serialize :content

  attr_reader :files

  # -- Callbacks ---------------------------------------------------------------
  after_save  :remove_attachments,
              :add_attachments

  # -- 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 if attachments
    end

    attachments.attach(@files)
  end

end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
comfortable_mexican_sofa-2.0.12 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.11 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.10 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.9 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.8 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.7 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.6 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.5 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.4 app/models/comfy/cms/fragment.rb
comfortable_mexican_sofa-2.0.3 app/models/comfy/cms/fragment.rb