Sha256: 71d7ce98bc1872246dac7b4f5e7a253561dd31a26d4cf9aa784a4e8db225ff4e

Contents?: true

Size: 1.59 KB

Versions: 3

Compression:

Stored size: 1.59 KB

Contents

module Cas
  class Content < ApplicationRecord
    include ::PgSearch
    extend ::FriendlyId

    friendly_id :title, use: :slugged
    acts_as_taggable

    serialize :metadata

    belongs_to :section
    belongs_to :category
    belongs_to :author, class_name: Cas::User
    has_many :images, ->{ where(media_type: :image).order("cas_media_files.order ASC") }, class_name: Cas::MediaFile, as: :attachable, dependent: :destroy
    has_many :attachments, ->{ where(media_type: :attachment).order("cas_media_files.order ASC") }, class_name: Cas::MediaFile, as: :attachable, dependent: :destroy
    has_one :cover_image, ->{ where(media_type: :image, cover: true) }, class_name: Cas::MediaFile, as: :attachable

    validates :title, presence: true

    before_validation :set_published_at
    before_save :cache_tags

    scope :published, ->{ where(published: true) }

    pg_search_scope :search, ->(query) do
      {
        query: query,
        against: [:title, :text, :location, :tags_cache],
        order_within_rank: "cas_contents.published_at DESC"
      }
    end

    def date_year
      date.year
    end

    def metadata
      if self[:metadata].is_a?(String)
        JSON.parse(self[:metadata])
      else
        super
      end
    end

    private

    def set_published_at
      if published_at.blank? && published
        self.published_at = Time.now
      end
    end

    # so we can fulltext search appropriatelly with pg_search
    def cache_tags
      category_name = "#{category.name if category.present?}"
      self.tags_cache = (tag_list + category_name).flatten.join(", ")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
cas-cms-0.1.2 app/models/cas/content.rb
cas-cms-0.1.1 app/models/cas/content.rb
cas-cms-0.1.0 app/models/cas/content.rb