lib/api_resource/associations.rb in api_resource-0.6.1 vs lib/api_resource/associations.rb in api_resource-0.6.2
- old
+ new
@@ -6,10 +6,11 @@
module Associations
#TODO: many of these methods should also force loading of the resource definition
extend ActiveSupport::Concern
extend ActiveSupport::Autoload
+ include ActiveModel::Dirty
autoload :AssociationProxy
autoload :BelongsToRemoteObjectProxy
autoload :HasManyRemoteObjectProxy
autoload :HasManyThroughRemoteObjectProxy
@@ -140,15 +141,22 @@
return self.find_namespaced_class_name(ret[1]) if ret
end
end
# TODO: add a special foreign_key option to associations
- def association_foreign_key_field(assoc)
+ def association_foreign_key_field(assoc, type = nil)
+
+ if type.nil? && has_many?(assoc)
+ type = :has_many
+ else
+ type = type.to_s.to_sym
+ end
+
# for now just use the association name
str = assoc.to_s.singularize.foreign_key
- if has_many?(assoc)
+ if type == :has_many
str = str.pluralize
end
str.to_sym
end
@@ -175,23 +183,19 @@
# TODO :Remove scopes from related_objects.
self.related_objects[:scopes] = self.related_objects[:scopes].clone
end
def define_association_as_attribute(assoc_type, assoc_name)
+ id_method_name = association_foreign_key_field(assoc_name, assoc_type)
+
# set up dirty tracking for associations, but only for ApiResource
# these methods are also used for ActiveRecord
# TODO: change this
if self.ancestors.include?(ApiResource::Base)
define_attribute_method(assoc_name)
+ define_attribute_method(id_method_name)
end
-
- id_method_name = assoc_name.to_s.singularize + "_id"
-
- if assoc_type.to_s == "has_many"
- id_method_name += "s"
- end
-
# TODO: Come up with a better implementation for the foreign key thing
# implement the rest of the active record methods, refactor this into something
# a little bit more sensible
# TODO: This should support saving the ids when they are modified and saving anything
@@ -221,14 +225,22 @@
def #{assoc_name}?
self.#{assoc_name}.internal_object.present?
end
def #{id_method_name}
- @attributes_cache[:#{id_method_name}] ||=
- @attributes[:#{id_method_name}] || self.#{assoc_name}.collect(&:id)
+ @attributes_cache[:#{id_method_name}] ||= begin
+ if @attributes.key?(:#{id_method_name})
+ @attributes[:#{id_method_name}]
+ else
+ self.#{assoc_name}.collect(&:id)
+ end
+ end
end
- def #{id_method_name}=(val)
+ def #{id_method_name}=(val, force = false)
+ unless @attributes_cache[:#{id_method_name}] == val
+ #{id_method_name}_will_change!
+ end
@attributes_cache[:#{id_method_name}] = val
end
EOE
end