def belongs_to(association_id, options = {})
reflection = create_belongs_to_reflection(association_id, options)
if reflection.options[:polymorphic]
association_accessor_methods(reflection, BelongsToPolymorphicAssociation)
module_eval do
before_save "association = instance_variable_get(\"@\#{reflection.name}\")\nif association && association.target\nif association.new_record?\nassociation.save(true)\nend\n\nif association.updated?\nself[\"\#{reflection.primary_key_name}\"] = association.id\nself[\"\#{reflection.options[:foreign_type]}\"] = association.class.base_class.name.to_s\nend\nend\n"
end
else
association_accessor_methods(reflection, BelongsToAssociation)
association_constructor_method(:build, reflection, BelongsToAssociation)
association_constructor_method(:create, reflection, BelongsToAssociation)
module_eval do
before_save "association = instance_variable_get(\"@\#{reflection.name}\")\nif !association.nil?\nif association.new_record?\nassociation.save(true)\nend\n\nif association.updated?\nself[\"\#{reflection.primary_key_name}\"] = association.id\nend\nend\n"
end
end
if options[:counter_cache]
cache_column = options[:counter_cache] == true ?
"#{self.to_s.underscore.pluralize}_count" :
options[:counter_cache]
module_eval(
"after_create '#{reflection.name}.class.increment_counter(\"#{cache_column}\", #{reflection.primary_key_name})" +
" unless #{reflection.name}.nil?'"
)
module_eval(
"before_destroy '#{reflection.name}.class.decrement_counter(\"#{cache_column}\", #{reflection.primary_key_name})" +
" unless #{reflection.name}.nil?'"
)
module_eval(
"#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)"
)
end
end