-
Notifications
You must be signed in to change notification settings - Fork 21.6k
/
belongs_to_association.rb
75 lines (61 loc) · 1.99 KB
/
belongs_to_association.rb
1
2
3
4
5
6
7
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
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
67
68
69
70
71
72
73
74
75
module ActiveRecord
module Associations
class BelongsToAssociation < AssociationProxy #:nodoc:
def initialize(owner, association_name, association_class_name, association_class_primary_key_name, options)
super
construct_sql
end
def reset
@target = nil
@loaded = false
end
def create(attributes = {})
record = @association_class.create(attributes)
replace(record, true)
record
end
def build(attributes = {})
record = @association_class.new(attributes)
replace(record, true)
record
end
def replace(obj, dont_save = false)
if obj.nil?
@target = @owner[@association_class_primary_key_name] = nil
else
raise_on_type_mismatch(obj) unless obj.nil?
@target = (AssociationProxy === obj ? obj.target : obj)
@owner[@association_class_primary_key_name] = obj.id unless obj.new_record?
@updated = true
end
@loaded = true
return (@target.nil? ? nil : self)
end
def updated?
@updated
end
protected
private
def find_target
if @options[:conditions]
@association_class.find(
@owner[@association_class_primary_key_name],
:conditions => interpolate_sql(@options[:conditions]),
:include => @options[:include]
)
else
@association_class.find(@owner[@association_class_primary_key_name], :include => @options[:include])
end
end
def foreign_key_present
!@owner[@association_class_primary_key_name].nil?
end
def target_obsolete?
@owner[@association_class_primary_key_name] != @target.id
end
def construct_sql
@finder_sql = "#{@association_class.table_name}.#{@association_class.primary_key} = #{@owner.id}"
end
end
end
end