Sha256: f770ec64eca06dd30a6ae614bdf77b54bf8e8904223bd7e9391c1ff47aaaacbb

Contents?: true

Size: 1.82 KB

Versions: 2

Compression:

Stored size: 1.82 KB

Contents

module CamaleonCms
  class Category < CamaleonCms::TermTaxonomy
    include CamaleonCms::CommonRelationships

    alias_attribute :site_id, :term_group
    alias_attribute :post_type_id, :status

    default_scope { where(taxonomy: :category) }
    scope :no_empty, -> { where('count > 0') } # return all categories that contains at least one post
    scope :empty, -> { where(count: [0, nil]) } # return all categories that does not contain any post
    # scope :parents, -> { where("term_taxonomy.parent_id IS NULL") }

    has_many :posts, foreign_key: :objectid, through: :term_relationships, source: :object
    has_many :children, class_name: 'CamaleonCms::Category', foreign_key: :parent_id, dependent: :destroy
    belongs_to :parent, class_name: 'CamaleonCms::Category', foreign_key: :parent_id, required: false
    belongs_to :post_type_parent, class_name: 'CamaleonCms::PostType', foreign_key: :parent_id,
                                  inverse_of: :categories, required: false
    belongs_to :site, required: false

    before_save :set_site
    before_destroy :set_posts_in_default_category

    # return the post type of this category
    def post_type
      cama_fetch_cache('post_type') do
        ctg = self
        loop do
          pt = ctg.post_type_parent
          ctg = ctg.parent
          break pt unless ctg
        end
      end
    end

    private

    def set_site
      self.site_id ||= post_type.site_id
      self.status ||= post_type.id
    end

    # rescue all posts to assign into default category if they don't have any category assigned
    def set_posts_in_default_category
      category_default = post_type.default_category
      return if category_default == self

      posts.each do |post|
        post.assign_category(category_default.id) if post.categories.where.not(id: id).blank?
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
camaleon_cms-2.7.2 app/models/camaleon_cms/category.rb
camaleon_cms-2.7.1 app/models/camaleon_cms/category.rb