Module: Concept::Relation::ReverseRelationExtension

Defined in:
app/models/concept/relation/reverse_relation_extension.rb

Instance Method Summary collapse

Instance Method Details

#create_with_reverse_relation(target_concept, attributes = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/models/concept/relation/reverse_relation_extension.rb', line 20

def create_with_reverse_relation(target_concept, attributes = {})
  relation_class = proxy_association.reflection.class_name.constantize
  ActiveRecord::Base.transaction do
    # The one direction
    scope = relation_class.where(owner_id: proxy_association.owner.id, target_id: target_concept.id)
    attributes = attributes.except(:rank) unless relation_class.rankable?
    scope.any? || scope.create!(attributes)

    if relation_class.bidirectional?
      # The reverse direction
      scope = relation_class.reverse_relation_class.where(owner_id: target_concept.id, target_id: proxy_association.owner.id)
      scope.any? || scope.create!(attributes)
    end
  end
end

#destroy_with_reverse_relation(target_concept) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/models/concept/relation/reverse_relation_extension.rb', line 36

def destroy_with_reverse_relation(target_concept)
  relation_class = proxy_association.reflection.class_name.constantize
  ActiveRecord::Base.transaction do
    relation_class.where(owner_id: proxy_association.owner.id, target_id: target_concept.id).load.each do |relation|
      relation.destroy
    end

    if relation_class.bidirectional?
      relation_class.reverse_relation_class.where(owner_id: target_concept.id, target_id: proxy_association.owner.id).load.each do |relation|
        relation.destroy
      end
    end
  end
end