2007-01-22 14:43:50 +01:00
|
|
|
module ActiveRecord
|
|
|
|
module Associations
|
|
|
|
class BelongsToAssociation < AssociationProxy #:nodoc:
|
|
|
|
def create(attributes = {})
|
2008-10-27 07:47:01 +01:00
|
|
|
replace(@reflection.create_association(attributes))
|
2007-01-22 14:43:50 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def build(attributes = {})
|
2008-10-27 07:47:01 +01:00
|
|
|
replace(@reflection.build_association(attributes))
|
2007-01-22 14:43:50 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def replace(record)
|
|
|
|
counter_cache_name = @reflection.counter_cache_column
|
|
|
|
|
|
|
|
if record.nil?
|
2008-05-18 06:22:34 +02:00
|
|
|
if counter_cache_name && !@owner.new_record?
|
2007-01-22 14:43:50 +01:00
|
|
|
@reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
|
|
|
|
end
|
|
|
|
|
|
|
|
@target = @owner[@reflection.primary_key_name] = nil
|
|
|
|
else
|
|
|
|
raise_on_type_mismatch(record)
|
|
|
|
|
|
|
|
if counter_cache_name && !@owner.new_record?
|
|
|
|
@reflection.klass.increment_counter(counter_cache_name, record.id)
|
|
|
|
@reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
|
|
|
|
end
|
|
|
|
|
|
|
|
@target = (AssociationProxy === record ? record.target : record)
|
|
|
|
@owner[@reflection.primary_key_name] = record.id unless record.new_record?
|
|
|
|
@updated = true
|
|
|
|
end
|
|
|
|
|
|
|
|
loaded
|
|
|
|
record
|
|
|
|
end
|
|
|
|
|
|
|
|
def updated?
|
|
|
|
@updated
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def find_target
|
|
|
|
@reflection.klass.find(
|
2008-06-02 08:35:38 +02:00
|
|
|
@owner[@reflection.primary_key_name],
|
|
|
|
:select => @reflection.options[:select],
|
2007-01-22 14:43:50 +01:00
|
|
|
:conditions => conditions,
|
2008-05-18 06:22:34 +02:00
|
|
|
:include => @reflection.options[:include],
|
2008-06-02 08:35:38 +02:00
|
|
|
:readonly => @reflection.options[:readonly]
|
2007-01-22 14:43:50 +01:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def foreign_key_present
|
|
|
|
!@owner[@reflection.primary_key_name].nil?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|