Class: ActiveRecord::Associations::HasOneAssociation

Inherits:
BelongsToAssociation show all
Defined in:
lib/gems/activerecord-2.2.2/lib/active_record/associations/has_one_association.rb

Overview

:nodoc:

Instance Method Summary collapse

Methods inherited from BelongsToAssociation

#updated?

Methods inherited from AssociationProxy

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

Constructor Details

#initialize(owner, reflection) ⇒ HasOneAssociation

Returns a new instance of HasOneAssociation.



4
5
6
7
# File 'lib/gems/activerecord-2.2.2/lib/active_record/associations/has_one_association.rb', line 4

def initialize(owner, reflection)
  super
  construct_sql
end

Dynamic Method Handling

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

Instance Method Details

#build(attrs = {}, replace_existing = true) ⇒ Object



21
22
23
24
25
# File 'lib/gems/activerecord-2.2.2/lib/active_record/associations/has_one_association.rb', line 21

def build(attrs = {}, replace_existing = true)
  new_record(replace_existing) do |reflection|
    reflection.build_association(attrs)
  end
end

#create(attrs = {}, replace_existing = true) ⇒ Object



9
10
11
12
13
# File 'lib/gems/activerecord-2.2.2/lib/active_record/associations/has_one_association.rb', line 9

def create(attrs = {}, replace_existing = true)
  new_record(replace_existing) do |reflection|
    reflection.create_association(attrs)
  end
end

#create!(attrs = {}, replace_existing = true) ⇒ Object



15
16
17
18
19
# File 'lib/gems/activerecord-2.2.2/lib/active_record/associations/has_one_association.rb', line 15

def create!(attrs = {}, replace_existing = true)
  new_record(replace_existing) do |reflection|
    reflection.create_association!(attrs)
  end
end

#replace(obj, dont_save = false) ⇒ Object



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
# File 'lib/gems/activerecord-2.2.2/lib/active_record/associations/has_one_association.rb', line 27

def replace(obj, dont_save = false)
  load_target

  unless @target.nil? || @target == obj
    if dependent? && !dont_save
      @target.destroy unless @target.new_record?
      @owner.clear_association_cache
    else
      @target[@reflection.primary_key_name] = nil
      @target.save unless @owner.new_record? || @target.new_record?
    end
  end

  if obj.nil?
    @target = nil
  else
    raise_on_type_mismatch(obj)
    set_belongs_to_association_for(obj)
    @target = (AssociationProxy === obj ? obj.target : obj)
  end

  @loaded = true

  unless @owner.new_record? or obj.nil? or dont_save
    return (obj.save ? self : false)
  else
    return (obj.nil? ? nil : self)
  end
end