Module: Comfy::Cms::WithCategories

Extended by:
ActiveSupport::Concern
Included in:
File, Page, Snippet
Defined in:
app/models/concerns/comfy/cms/with_categories.rb

Instance Method Summary collapse

Instance Method Details

#category_idsObject



29
30
31
# File 'app/models/concerns/comfy/cms/with_categories.rb', line 29

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

#sync_categoriesObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/models/concerns/comfy/cms/with_categories.rb', line 33

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