Sha256: 4378976c9596ec94e35e2f4a833171aad0b000e262d09b785a0c9ce12778a26e

Contents?: true

Size: 1.08 KB

Versions: 1

Compression:

Stored size: 1.08 KB

Contents

# encoding: utf-8

module PagesCore
  module PageModel
    module Images
      extend ActiveSupport::Concern

      included do
        belongs_to_image :image
        belongs_to_image :meta_image, class_name: "Image"
        has_many :page_images, -> { order("position") }
        has_many(
          :images,
          -> { where("`page_images`.`primary` = ?", false).order("position") },
          through: :page_images
        )

        after_save :ensure_page_images_contains_primary_image
      end

      def image?
        image_id?
      end

      def image
        super.try { |i| i.localize(locale) }
      end

      def images
        super.in_locale(locale)
      end

      def page_images
        super.in_locale(locale)
      end

      private

      def ensure_page_images_contains_primary_image
        return if !image_id? || !image_id_changed?
        page_image = page_images.find_by(image_id: image_id)
        if page_image
          page_image.update(primary: true)
        else
          page_images.create(image_id: image_id, primary: true)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pages_core-3.5.1 app/models/concerns/pages_core/page_model/images.rb