Sha256: 6d4e4c71fd415ffb612e10889500b292850150c130dc54432aa05e5b7ffafb8f

Contents?: true

Size: 1.25 KB

Versions: 17

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module Comfy::Cms::WithCategories

  extend ActiveSupport::Concern

  included do
    has_many :categorizations,
      as:         :categorized,
      class_name: "Comfy::Cms::Categorization",
      dependent:  :destroy
    has_many :categories,
      through:    :categorizations,
      class_name: "Comfy::Cms::Category"

    attr_writer :category_ids

    after_save :sync_categories

    scope :for_category, ->(*categories) {
      if (categories = [categories].flatten.compact).present?
        distinct
          .joins(categorizations: :category)
          .where("comfy_cms_categories.label" => categories)
      end
    }
  end

  def category_ids
    @category_ids ||= categories.pluck(:id)
  end

  def sync_categories
    return unless category_ids.is_a?(Array)

    scope = Comfy::Cms::Category.of_type(self.class.to_s)
    existing_ids = scope.pluck(:id)

    ids_to_add = category_ids.map(&:to_i)

    # adding categorizations
    ids_to_add.each do |id|
      if (category = scope.find_by_id(id))
        category.categorizations.create(categorized: self)
      end
    end

    # removing categorizations
    ids_to_remove = existing_ids - ids_to_add
    categorizations.where(category_id: ids_to_remove).destroy_all
  end

end

Version data entries

17 entries across 17 versions & 6 rubygems

Version Path
comfortable_mexican_sofa-2.0.19 app/models/concerns/comfy/cms/with_categories.rb
PixelForce_ETS-0.0.2 app/models/concerns/comfy/cms/with_categories.rb
PixelForce_ETS-0.0.1 app/models/concerns/comfy/cms/with_categories.rb
kcyEtsTest2-0.0.4 app/models/concerns/comfy/cms/with_categories.rb
kcyEtsTest2-0.0.3 app/models/concerns/comfy/cms/with_categories.rb
kcyEtsTest2-0.0.2 app/models/concerns/comfy/cms/with_categories.rb
kcyEtsTest2-0.0.1 app/models/concerns/comfy/cms/with_categories.rb
kcyEtsTest-0.0.1 app/models/concerns/comfy/cms/with_categories.rb
kcyEtsTest-2.2.19 app/models/concerns/comfy/cms/with_categories.rb
ComfortableMexicanSofa-2.0.18 app/models/concerns/comfy/cms/with_categories.rb
kcy1-1.0 app/models/concerns/comfy/cms/with_categories.rb
comfortable_mexican_sofa-2.0.18 app/models/concerns/comfy/cms/with_categories.rb
comfortable_mexican_sofa-2.0.17 app/models/concerns/comfy/cms/with_categories.rb
comfortable_mexican_sofa-2.0.16 app/models/concerns/comfy/cms/with_categories.rb
comfortable_mexican_sofa-2.0.15 app/models/concerns/comfy/cms/with_categories.rb
comfortable_mexican_sofa-2.0.14 app/models/concerns/comfy/cms/with_categories.rb
comfortable_mexican_sofa-2.0.13 app/models/concerns/comfy/cms/with_categories.rb