class Cdao::Subject < Cdao::Base default_scope { joins(:library_subjects) .where(cdao_library_subjects: { library_id: [Cdao::Library.find_by(key: "JurisprudenceEncyclopedia").try(:id)] }) } has_ancestry has_many :library_subjects, dependent: :restrict_with_error accepts_nested_attributes_for :library_subjects, allow_destroy: true has_many :libraries, through: :library_subjects alias_attribute :producttitles, :libraries validates :name, presence: true validates :name, uniqueness: { scope: %i[ancestry] } scope :byproduct, lambda { |id| joins(:library_subjects).where(library_subjects: { library_id: id }) } scope :for_lib, lambda { |*ids| product_key = ids.shift where(arel_table[:id].in(ids).or(arel_table[:library_id].eq(product_key))) } scope :with_parent, -> { where(arel_table[:ancestry].not_eq nil) } state_machine initial: :published do event :publish do transition from: :activated, to: :published end event :unpublish do transition from: :published, to: :activated end end def lineage_name path.map(&:name).join("; ") end def name_with_product_names product_names = libraries.map(&:name).reject(&:blank?).join(", ") return name if product_names.blank? [name, "(#{product_names})"].join(" ") end end