class Document < ApplicationRecord
  has_many :content_items

  validates :content_id, presence: true, uuid: true

  validates :locale, inclusion: {
    in: I18n.available_locales.map(&:to_s),
    message: 'must be a supported locale'
  }

  def draft
    draft_items = content_items.where(content_store: "draft")

    if draft_items.size > 1
      raise "There should only be one draft item"
    end

    draft_items.first
  end

  def live
    live_items = content_items.where(content_store: "live")

    if live_items.size > 1
      raise "There should only be one previous published or unpublished item"
    end

    live_items.first
  end
end

class Document < ApplicationRecord
  has_many :content_items
  has_one :draft, -> { where(content_store: "draft") }, class_name: ContentItem
  has_one :live, -> { where(content_store: "live") }, class_name: ContentItem

  validates :content_id, presence: true, uuid: true

  validates :locale, inclusion: {
    in: I18n.available_locales.map(&:to_s),
    message: 'must be a supported locale'
  }
end

Use ActiveRecord relations for draft and live
Use ActiveRecord relations for draft and live

This uses the ActiveRecord relations and associated caching for
accessing draft and live items.

This doesn't have the check for duplicate items anymore as I wasn't sure
how it could be integrated and I'm expecting this not to be too great a
concern as DB constraints will soon apply.
