Sha256: 667421ee71b14b9c5fae687122b5e5d4f5d9cffca6c7594994f1008375c436a9
Contents?: true
Size: 1.27 KB
Versions: 12
Compression:
Stored size: 1.27 KB
Contents
# frozen_string_literal: true module Occams::Cms::WithCategories extend ActiveSupport::Concern included do has_many :categorizations, as: :categorized, class_name: 'Occams::Cms::Categorization', dependent: :destroy has_many :categories, through: :categorizations, class_name: 'Occams::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('occams_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 = Occams::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
12 entries across 12 versions & 1 rubygems