Class: ActiveFedora::Associations::HasAndBelongsToManyAssociation

Inherits:
CollectionAssociation show all
Defined in:
lib/active_fedora/associations/has_and_belongs_to_many_association.rb

Overview

:nodoc:

Instance Attribute Summary

Attributes inherited from CollectionAssociation

#proxy

Attributes inherited from Association

#inversed, #owner, #reflection, #target

Instance Method Summary collapse

Methods inherited from CollectionAssociation

#add_to_target, #any?, #build, #concat, #create, #create!, #delete, #delete_all, #destroy, #destroy_all, #empty?, #find, #first, #ids_reader, #ids_writer, #include?, #last, #load_from_solr, #load_target, #null_scope?, #reader, #replace, #reset, #scope, #select, #size, #target=, #to_ary, #writer

Methods inherited from Association

#association_scope, #initialize_attributes, #load_target, #loaded!, #loaded?, #reload, #reset, #reset_scope, #scope, #set_inverse_instance, #stale_target?, #target_scope

Constructor Details

#initialize(owner, reflection) ⇒ HasAndBelongsToManyAssociation

Returns a new instance of HasAndBelongsToManyAssociation.



5
6
7
# File 'lib/active_fedora/associations/has_and_belongs_to_many_association.rb', line 5

def initialize(owner, reflection)
  super
end

Instance Method Details

#concat_records(*records) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/active_fedora/associations/has_and_belongs_to_many_association.rb', line 35

def concat_records(*records)
  result = true

  records.flatten.each do |record|
    raise_on_type_mismatch!(record)
    add_to_target(record) do |_r|
      result &&= insert_record(record)
    end
  end

  result && records
end

#count(_options = {}) ⇒ Object

In a HABTM, just look in the RDF, no need to run a count query from solr.



49
50
51
# File 'lib/active_fedora/associations/has_and_belongs_to_many_association.rb', line 49

def count(_options = {})
  owner[reflection.foreign_key].size
end

#insert_record(record, force = true, validate = true) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/active_fedora/associations/has_and_belongs_to_many_association.rb', line 9

def insert_record(record, force = true, validate = true)
  if record.new_record?
    if force
      record.save!
    else
      return false unless record.save(validate: validate)
    end
  end
  owner[reflection.foreign_key] ||= []
  owner[reflection.foreign_key] += [record.id]

  # Only if they've explicitly stated the inverse in the options
  if reflection.options[:inverse_of]
    inverse = reflection.inverse_of
    if owner.new_record?
      ActiveFedora::Base.logger.warn("has_and_belongs_to_many #{reflection.inspect} is cowardly refusing to insert the inverse relationship into #{record}, because #{owner} is not persisted yet.")
    elsif inverse.has_and_belongs_to_many?
      record[inverse.foreign_key] ||= []
      record[inverse.foreign_key] += [owner.id]
      record.save
    end
  end

  true
end