Froze rails gems
[depot.git] / vendor / rails / activerecord / lib / active_record / associations / belongs_to_association.rb
1 module ActiveRecord
2 module Associations
3 class BelongsToAssociation < AssociationProxy #:nodoc:
4 def create(attributes = {})
5 replace(@reflection.create_association(attributes))
6 end
7
8 def build(attributes = {})
9 replace(@reflection.build_association(attributes))
10 end
11
12 def replace(record)
13 counter_cache_name = @reflection.counter_cache_column
14
15 if record.nil?
16 if counter_cache_name && !@owner.new_record?
17 @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
18 end
19
20 @target = @owner[@reflection.primary_key_name] = nil
21 else
22 raise_on_type_mismatch(record)
23
24 if counter_cache_name && !@owner.new_record?
25 @reflection.klass.increment_counter(counter_cache_name, record.id)
26 @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
27 end
28
29 @target = (AssociationProxy === record ? record.target : record)
30 @owner[@reflection.primary_key_name] = record.id unless record.new_record?
31 @updated = true
32 end
33
34 loaded
35 record
36 end
37
38 def updated?
39 @updated
40 end
41
42 private
43 def find_target
44 @reflection.klass.find(
45 @owner[@reflection.primary_key_name],
46 :select => @reflection.options[:select],
47 :conditions => conditions,
48 :include => @reflection.options[:include],
49 :readonly => @reflection.options[:readonly]
50 )
51 end
52
53 def foreign_key_present
54 !@owner[@reflection.primary_key_name].nil?
55 end
56 end
57 end
58 end