Sha256: 70019d083ee5b80842920d3823e07c1c0418bf64e31e3ee6e6ea236f88c2aba3

Contents?: true

Size: 1.9 KB

Versions: 3

Compression:

Stored size: 1.9 KB

Contents

module PagesCms
  class Page < ActiveRecord::Base
    belongs_to  :account
    belongs_to  :parent, class_name: 'Page'

    has_many    :children, class_name: 'Page', foreign_key: 'parent_id', dependent: :destroy
    has_many    :page_blocks, dependent: :destroy
    has_one     :sidebar, dependent: :destroy
    has_many    :sliders, dependent: :destroy

    accepts_nested_attributes_for :sidebar,     allow_destroy: true
    accepts_nested_attributes_for :sliders,     allow_destroy: true
    accepts_nested_attributes_for :page_blocks, allow_destroy: true

    validates :title, presence: true
    validates :slug,  presence: true

    validate  :has_account,            if: :no_errors
    validate  :unique_slug_create,     if: :no_errors, on: :create
    validate  :unique_slug_save,       if: :no_errors, on: :update
    validate  :slug_has_no_spaces,     if: :no_errors
    validate  :page_parent_of_itself,  if: :no_errors

    before_validation :parameterize_slug

    private
      def has_account
        if self.account.nil?
          errors.add(:base, 'Must be associated with an account')
        end
      end

      def parameterize_slug
        self.slug = title.parameterize
      end

      def slug_has_no_spaces
        if slug.index(/\s/) != nil
          errors.add(:slug, 'must have no whitespace')
        end
      end

      def page_parent_of_itself
        if self.parent_id != nil && self.parent_id == self.id
          errors.add(:base, 'Cannot be a sub-page of itself')
        end
      end

      def unique_slug_save
        if self.account.pages.where(slug: self.slug).count >= 2
          errors.add(:base, 'A page already exists by this name!')
        end
      end

      def unique_slug_create
        if self.account.pages.where(slug: self.slug).present?
          errors.add(:base, 'A page already exists by this name!')
        end
      end

      def no_errors
        errors.empty?
      end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pages_cms-2.2.3 app/models/pages_cms/page.rb
pages_cms-2.2.2 app/models/pages_cms/page.rb
pages_cms-2.2.1 app/models/pages_cms/page.rb