Module: DataMapper::Associations::OneToMany

Extended by:
DataMapper::Assertions
Defined in:
lib/dm-core/associations/one_to_many.rb

Defined Under Namespace

Classes: Proxy

Class Method Summary collapse

Methods included from DataMapper::Assertions

assert_kind_of

Class Method Details

.setup(name, model, options = {}) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Setup one to many relationship between two models -



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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/dm-core/associations/one_to_many.rb', line 9

def self.setup(name, model, options = {})
  assert_kind_of 'name',    name,    Symbol
  assert_kind_of 'model',   model,   Model
  assert_kind_of 'options', options, Hash

  repository_name = model.repository.name

  model.class_eval <<-EOS, __FILE__, __LINE__
    def #{name}(query = {})
      #{name}_association.all(query)
    end

    def #{name}=(children)
      #{name}_association.replace(children)
    end

    private

    def #{name}_association
      @#{name}_association ||= begin
        unless relationship = model.relationships(#{repository_name.inspect})[#{name.inspect}]
          raise ArgumentError, "Relationship #{name.inspect} does not exist in \#{model}"
        end
        association = Proxy.new(relationship, self)
        parent_associations << association
        association
      end
    end
  EOS

  model.relationships(repository_name)[name] = if options.has_key?(:through)
    opts = options.dup

    if opts.key?(:class_name) && !opts.key?(:child_key)
      warn(<<-EOS.margin)
        You have specified #{model.base_model.name}.has(#{name.inspect}) with :class_name => #{opts[:class_name].inspect}. You probably also want to specify the :child_key option.
      EOS
    end

    opts[:child_model]            ||= opts.delete(:class_name)  || Extlib::Inflection.classify(name)
    opts[:parent_model]             =   model
    opts[:repository_name]          =   repository_name
    opts[:near_relationship_name]   =   opts.delete(:through)
    opts[:remote_relationship_name] ||= opts.delete(:remote_name) || name
    opts[:parent_key]               =   opts[:parent_key]
    opts[:child_key]                =   opts[:child_key]

    RelationshipChain.new( opts )
  else
    Relationship.new(
      name,
      repository_name,
      options.fetch(:class_name, Extlib::Inflection.classify(name)),
      model,
      options
    )
  end
end