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
# 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)

    # 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

#destroy_with_reverse_relation(target_concept) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/models/concept/relation/reverse_relation_extension.rb', line 34

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

    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