Module: DataMapper::Associations::OneToOne

Public Visibility

Public Instance Method Summary

#setup(name, model, options = {})

Setup one to one relationship between two models.

Public Instance Method Details

setup

public setup(name, model, options = {})

Setup one to one relationship between two models

[View source]


8
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
# File 'dm-core/lib/dm-core/associations/one_to_one.rb', line 8

def setup(name, model, options = {})
  raise ArgumentError, "+name+ should be a Symbol, but was #{name.class}", caller     unless Symbol === name
  raise ArgumentError, "+options+ should be a Hash, but was #{options.class}", caller unless Hash   === options

  repository_name = model.repository.name

  model.class_eval "# FIXME: I think this is a subtle bug.  Since we return the resource directly\n# and not the proxy, then the proxy methods (like save) won't be fired off\n# as needed.  To fix this we may need a subclass of OneToMany that returns\n# a proxy object with just a single entry.\ndef \#{name}\n\#{name}_association.first\nend\n\ndef \#{name}=(child_resource)\n\#{name}_association.replace(child_resource.nil? ? [] : [ child_resource ])\nend\n\nprivate\n\ndef \#{name}_association\n@\#{name}_association ||= begin\nrelationship = self.class.relationships(\#{repository_name.inspect})[:\#{name}]\nassociation = Associations::OneToMany::Proxy.new(relationship, self)\nparent_associations << association\nassociation\nend\nend\n", __FILE__, __LINE__

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




    RelationshipChain.new(
      :child_model_name         => options.fetch(:class_name, Extlib::Inflection.classify(name)),
      :parent_model_name        => model.name,
      :repository_name          => repository_name,
      :near_relationship_name   => options[:through],
      :remote_relationship_name => options.fetch(:remote_name, name),
      :parent_key               => options[:parent_key],
      :child_key                => options[:child_key]
    )
  else
    Relationship.new(
      Extlib::Inflection.underscore(Extlib::Inflection.demodulize(model.name)).to_sym,
      repository_name,
      options.fetch(:class_name, Extlib::Inflection.classify(name)),
      model.name,
      options
    )
  end
end