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
|
# File 'lib/classy-inheritance.rb', line 7
def has_one(association_id, options = {})
if options[:through]
reflection = create_has_one_through_reflection(association_id, options)
association_accessor_methods(reflection, ActiveRecord::Associations::HasOneThroughAssociation)
else
reflection = create_has_one_reflection(association_id, options)
ivar = "@#{reflection.name}"
method_name = "has_one_after_save_for_#{reflection.name}".to_sym
define_method(method_name) do
association = instance_variable_get(ivar) if instance_variable_defined?(ivar)
primary_key = reflection.options[:primary_key] || :id
if !association.nil? && (new_record? || association.new_record? || association[reflection.primary_key_name] != send(primary_key))
association[reflection.primary_key_name] = send(primary_key)
association.save(true)
end
end
after_save method_name
add_single_associated_validation_callbacks(reflection.name) if options[:validate] == true
association_accessor_methods(reflection, ActiveRecord::Associations::HasOneAssociation)
association_constructor_method(:build, reflection, ActiveRecord::Associations::HasOneAssociation)
association_constructor_method(:create, reflection, ActiveRecord::Associations::HasOneAssociation)
configure_dependency_for_has_one(reflection)
end
end
|