lib/db_memoize/model.rb in db_memoize-0.2.2 vs lib/db_memoize/model.rb in db_memoize-0.2.3

- old
+ new

@@ -24,17 +24,11 @@ value end def unmemoize(method_name = :all) - if method_name != :all - # FIXME: this works, but isn't immediately visible on the record. - # See also note in create_memoized_value. - memoized_values.where(method_name: method_name).delete_all - else - memoized_values.clear - end + self.class.unmemoize id, method_name end # # Used to set multiple memoized values in one go. # @@ -94,11 +88,11 @@ entity_table_name: table_name, entity_id: Helpers.find_ids(records_or_ids) } conditions[:method_name] = method_name unless method_name == :all - DbMemoize::Value.where(conditions).delete_all + DbMemoize::Value.where(conditions).delete_all_ordered end def memoize_values(records_or_ids, values, *args) # [TODO] - when creating many memoized values: should we even support arguments here? transaction do @@ -128,11 +122,26 @@ end def create_memoized_values_association unless reflect_on_association(:memoized_values) conditions = { entity_table_name: table_name } + + # By defining this before_destroy callback we make sure **we** delete all + # memoized values before Rails deletes those via `has_many dependent: + # This leads to has_many later on not finding any values to be deleted. + # + # It would be nice if there was a `dependent: :manual/:noop` option. + # + # **Note:** before_destroy must be called before memoized_values is + # set up, to make sure that these things happen in the right order. + # + before_destroy do |rec| + rec.memoized_values.delete_all_ordered + end + has_many :memoized_values, -> { where(conditions) }, dependent: :delete_all, class_name: 'DbMemoize::Value', foreign_key: :entity_id + end end end end end