3 class HasOneAssociation
< BelongsToAssociation
#:nodoc:
4 def initialize(owner
, reflection
)
9 def create(attrs
= {}, replace_existing
= true)
10 new_record(replace_existing
) do |reflection
|
11 reflection
.create_association(attrs
)
15 def create
!(attrs
= {}, replace_existing
= true)
16 new_record(replace_existing
) do |reflection
|
17 reflection
.create_association
!(attrs
)
21 def build(attrs
= {}, replace_existing
= true)
22 new_record(replace_existing
) do |reflection
|
23 reflection
.build_association(attrs
)
27 def replace(obj
, dont_save
= false)
30 unless @target.nil? || @target == obj
31 if dependent
? && !dont_save
32 @target.destroy
unless @target.new_record
?
33 @owner.clear_association_cache
35 @target[@reflection.primary_key_name
] = nil
36 @target.save
unless @owner.new_record
? || @target.new_record
?
43 raise_on_type_mismatch(obj
)
44 set_belongs_to_association_for(obj
)
45 @target = (AssociationProxy
=== obj
? obj
.target
: obj
)
50 unless @owner.new_record
? or obj
.nil? or dont_save
51 return (obj
.save
? self : false)
53 return (obj
.nil? ? nil : self)
59 if @reflection.options
[:primary_key]
60 @owner.class.quote_value(@owner.send(@reflection.options
[:primary_key]))
68 @reflection.klass
.find(:first,
69 :conditions => @finder_sql,
70 :select => @reflection.options
[:select],
71 :order => @reflection.options
[:order],
72 :include => @reflection.options
[:include],
73 :readonly => @reflection.options
[:readonly]
79 when @reflection.options
[:as]
81 "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_id = #{owner_quoted_id} AND " +
82 "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_type = #{@owner.class.quote_value(@owner.class.base_class.name.to_s)}"
84 @finder_sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{owner_quoted_id}"
86 @finder_sql << " AND (#{conditions})" if conditions
91 set_belongs_to_association_for(create_scoping
)
92 { :create => create_scoping
}
95 def new_record(replace_existing
)
96 # Make sure we load the target first, if we plan on replacing the existing
97 # instance. Otherwise, if the target has not previously been loaded
98 # elsewhere, the instance we create will get orphaned.
99 load_target
if replace_existing
100 record
= @reflection.klass
.send(:with_scope, :create => construct_scope
[:create]) do
105 replace(record
, true)
107 record
[@reflection.primary_key_name
] = @owner.id
unless @owner.new_record
?