Class: ActiveRecord::Associations::HasManyThroughAssociation

Inherits:
HasManyAssociation show all
Defined in:
lib/active_record/associations/has_many_through_association.rb

Overview

:nodoc:

Direct Known Subclasses

HasOneThroughAssociation

Instance Method Summary collapse

Methods inherited from AssociationCollection

#<<, #any?, #build, #clear, #count, #delete, #delete_all, #destroy, #destroy_all, #empty?, #find, #first, #include?, #last, #length, #proxy_respond_to?, #replace, #reset, #sum, #to_ary, #transaction, #uniq

Methods inherited from AssociationProxy

#===, #aliased_table_name, #inspect, #loaded, #loaded?, #proxy_owner, #proxy_reflection, #proxy_respond_to?, #proxy_target, #reload, #reset, #respond_to?, #send, #target, #target=

Constructor Details

#initialize(owner, reflection) ⇒ HasManyThroughAssociation

Returns a new instance of HasManyThroughAssociation.



4
5
6
7
# File 'lib/active_record/associations/has_many_through_association.rb', line 4

def initialize(owner, reflection)
  reflection.check_validity!
  super
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class ActiveRecord::Associations::AssociationCollection

Instance Method Details

#create(attrs = nil) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/active_record/associations/has_many_through_association.rb', line 18

def create(attrs = nil)
  transaction do
    object = if attrs
      @reflection.klass.send(:with_scope, :create => attrs) {
        @reflection.create_association
      }
    else
      @reflection.create_association
    end
    raise_on_type_mismatch(object)
    add_record_to_target_with_callbacks(object) do |r|
      insert_record(object, false)
    end
    object
  end
end

#create!(attrs = nil) ⇒ Object



11
12
13
14
15
16
# File 'lib/active_record/associations/has_many_through_association.rb', line 11

def create!(attrs = nil)
  transaction do
    self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.create_association! } : @reflection.create_association!)
    object
  end
end

#sizeObject

Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn’t been loaded and calling collection.size if it has. If it’s more likely than not that the collection does have a size larger than zero, and you need to fetch that collection afterwards, it’ll take one fewer SELECT query if you use #length.



38
39
40
41
42
# File 'lib/active_record/associations/has_many_through_association.rb', line 38

def size
  return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
  return @target.size if loaded?
  return count
end