Class: NinjaModel::Associations::CollectionAssociation

Inherits:
Association
  • Object
show all
Defined in:
lib/ninja_model/associations/collection_association.rb

Direct Known Subclasses

HasManyAssociation

Instance Attribute Summary collapse

Attributes inherited from Association

#owner, #reflection, #target

Instance Method Summary collapse

Methods inherited from Association

#association_scope, #klass, #load_target, #loaded!, #loaded?, #reload, #reset_scope, #scoped, #set_inverse_instance, #stale_target?, #target_scope

Constructor Details

#initialize(owner, reflection) ⇒ CollectionAssociation

Returns a new instance of CollectionAssociation.



8
9
10
11
# File 'lib/ninja_model/associations/collection_association.rb', line 8

def initialize(owner, reflection)
  super
  @proxy = CollectionProxy.new(self)
end

Instance Attribute Details

#proxyObject (readonly)

Returns the value of attribute proxy.



4
5
6
# File 'lib/ninja_model/associations/collection_association.rb', line 4

def proxy
  @proxy
end

Instance Method Details

#add_to_target(record) {|record| ... } ⇒ Object

def create!(attributes = {}, options = {}, &block)

create_record(attributes, options, true, &block)

end

Yields:

  • (record)


59
60
61
62
63
# File 'lib/ninja_model/associations/collection_association.rb', line 59

def add_to_target(record)
  yield(record) if block_given?
  @target << record
  record
end

#build(attributes = {}, options = {}, &block) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/ninja_model/associations/collection_association.rb', line 41

def build(attributes = {}, options = {}, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| build(attr, options, &block) }
  else
    add_to_target(build_record(attributes, options)) do |record|
      yield(record) if block_given?
    end
  end
end

#first(*args) ⇒ Object

def find(*args)

if block_given?
  load_target.find(*args) { |*block_args| yield(*block_args) }
else
  scoped.find(*args)
end

end



33
34
35
# File 'lib/ninja_model/associations/collection_association.rb', line 33

def first(*args)
  first_or_last(:first, *args)
end

#last(*args) ⇒ Object



37
38
39
# File 'lib/ninja_model/associations/collection_association.rb', line 37

def last(*args)
  first_or_last(:last, *args)
end

#reader(force_reload = false) ⇒ Object



13
14
15
16
17
18
# File 'lib/ninja_model/associations/collection_association.rb', line 13

def reader(force_reload = false)
  if force_reload
    klass.uncached { reload }
  end
  proxy
end

#resetObject



20
21
22
23
# File 'lib/ninja_model/associations/collection_association.rb', line 20

def reset
  @loaded = false
  @target = []
end