Class: Syncano::ActiveRecord::Association::HasMany

Inherits:
Base
  • Object
show all
Defined in:
lib/syncano/active_record/association/has_many.rb

Overview

Class for has many association

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#belongs_to?, #has_one?, #initialize

Constructor Details

This class inherits a constructor from Syncano::ActiveRecord::Association::Base

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object (private)

Overwritten method_missing for handling scope methods

Parameters:

  • name (String)
  • args (Array)


57
58
59
60
61
62
63
64
65
# File 'lib/syncano/active_record/association/has_many.rb', line 57

def method_missing(name, *args)
  scope_builder = Syncano::ActiveRecord::ScopeBuilder.new(associated_model).by_parent_id(source.id)

  if scope_builder.respond_to?(name) || !source.scopes[name].nil?
    scope_builder.send(name, *args)
  else
    super
  end
end

Instance Attribute Details

#associated_modelObject

Returns the value of attribute associated_model.



8
9
10
# File 'lib/syncano/active_record/association/has_many.rb', line 8

def associated_model
  @associated_model
end

#foreign_keyObject

Returns the value of attribute foreign_key.



8
9
10
# File 'lib/syncano/active_record/association/has_many.rb', line 8

def foreign_key
  @foreign_key
end

#source_modelObject

Returns the value of attribute source_model.



8
9
10
# File 'lib/syncano/active_record/association/has_many.rb', line 8

def source_model
  @source_model
end

Instance Method Details

#<<(object) ⇒ Object

Adds object to the related collection by setting foreign key

Parameters:

  • object (Object)

Returns:

  • (Object)


40
41
42
43
44
# File 'lib/syncano/active_record/association/has_many.rb', line 40

def <<(object)
  object.send("#{foreign_key}=", source.id)
  object.save unless object.new_record?
  object
end

#buildObject

Builds new associated object

Returns:

  • (Object)


27
28
29
# File 'lib/syncano/active_record/association/has_many.rb', line 27

def build
  associated_model.new(foreign_key => source.id)
end

#createObject

Creates new associated object

Returns:

  • (Object)


33
34
35
# File 'lib/syncano/active_record/association/has_many.rb', line 33

def create
  associated_model.create(foreign_key => source.id)
end

#has_many?TrueClass

Checks if association is has_many type

Returns:

  • (TrueClass)


12
13
14
# File 'lib/syncano/active_record/association/has_many.rb', line 12

def has_many?
  true
end

#scope_builder(source) ⇒ Syncano::ActiveRecord::Association::HasMany

Returns new associaton object with source object set

Parameters:

  • source (Object)

Returns:



19
20
21
22
23
# File 'lib/syncano/active_record/association/has_many.rb', line 19

def scope_builder(source)
  association = self.dup
  association.source = source
  association
end