1 # frozen_string_literal: true
 
   3 # == Schema Information
 
   5 # Table name: relations
 
   7 #  relation_id  :bigint           not null, primary key
 
   8 #  changeset_id :bigint           not null
 
   9 #  timestamp    :datetime         not null
 
  10 #  version      :bigint           not null, primary key
 
  11 #  visible      :boolean          default(TRUE), not null
 
  12 #  redaction_id :integer
 
  16 #  relations_changeset_id_idx  (changeset_id)
 
  17 #  relations_timestamp_idx     (timestamp)
 
  21 #  relations_changeset_id_fkey  (changeset_id => changesets.id)
 
  22 #  relations_redaction_id_fkey  (redaction_id => redactions.id)
 
  25 class OldRelation < ApplicationRecord
 
  26   self.table_name = "relations"
 
  28   # NOTE: this needs to be included after the table name changes, or
 
  29   # the queries generated by Redactable will use the wrong table name.
 
  33   belongs_to :redaction, :optional => true
 
  34   belongs_to :current_relation, :class_name => "Relation", :foreign_key => "relation_id", :inverse_of => :old_relations
 
  36   has_many :old_members, -> { order(:sequence_id) }, :class_name => "OldRelationMember", :foreign_key => [:relation_id, :version], :inverse_of => :old_relation
 
  37   has_many :old_tags, :class_name => "OldRelationTag", :foreign_key => [:relation_id, :version], :inverse_of => :old_relation
 
  39   validates :changeset, :associated => true
 
  40   validates :timestamp, :presence => true
 
  41   validates :visible, :inclusion => [true, false]
 
  43   def self.from_relation(relation)
 
  44     old_relation = OldRelation.new
 
  45     old_relation.visible = relation.visible
 
  46     old_relation.changeset_id = relation.changeset_id
 
  47     old_relation.timestamp = relation.timestamp
 
  48     old_relation.relation_id = relation.id
 
  49     old_relation.version = relation.version
 
  50     old_relation.members = relation.members
 
  51     old_relation.tags = relation.tags
 
  55   def save_with_dependencies!
 
  59       tag = OldRelationTag.new
 
  62       tag.relation_id = relation_id
 
  67     members.each_with_index do |m, i|
 
  68       member = OldRelationMember.new
 
  69       member.id = [relation_id, version, i]
 
  70       member.member_type = m[0].classify
 
  71       member.member_id = m[1]
 
  72       member.member_role = m[2]
 
  78     @members ||= old_members.collect do |member|
 
  79       [member.member_type, member.member_id, member.member_role]
 
  84     @tags ||= old_tags.to_h { |t| [t.k, t.v] }
 
  87   attr_writer :members, :tags
 
  89   # Temporary method to match interface to relations
 
  94   # Pretend we're not in any relations
 
  95   def containing_relation_members
 
  99   # check whether this element is the latest version - that is,
 
 100   # has the same version as its "current" counterpart.
 
 102     current_relation.version == version