JackDanger / permanent_records

Rails Plugin - soft-delete your ActiveRecord records. It's like an explicit version of ActsAsParanoid
https://jdanger.com
MIT License
272 stars 64 forks source link

Counter cache doesn't work with polymorphic association #77

Closed n-rodriguez closed 8 years ago

n-rodriguez commented 8 years ago

It breaks here with NameError: uninitialized constant Commentable

n-rodriguez commented 8 years ago

The quick and dirty patch (in config/initializers/permanent_records.rb) :

require 'permanent_records'

# Patch PermanentRecords to not check for counter_cache on polymorphic association

module PermanentRecordsPatch
  def self.included(base)
    base.send(:include, InstanceMethods)
    base.class_eval do
      alias_method_chain :each_counter_cache, :patch
    end
  end

  module InstanceMethods

    def each_counter_cache_with_patch
      _reflections.each do |name, reflection|
        # Here the patch
        next if reflection.polymorphic?
        #
        associated_class = association(name).reflection.class_name.constantize
        next unless reflection.belongs_to? && reflection.counter_cache_column
        yield(associated_class,
              reflection.counter_cache_column,
              send(reflection.foreign_key))
      end
    end

  end
end

unless PermanentRecords::ActiveRecord.included_modules.include?(PermanentRecordsPatch)
  PermanentRecords::ActiveRecord.send(:include, PermanentRecordsPatch)
end
drakmail commented 8 years ago

Oh, I'll fix it tomorrow

n-rodriguez commented 8 years ago

Oh, I'll fix it tomorrow

Ok. As I said this is a quick and dirty patch. I don't know if counter_cache works with polymorphic associations. By looking at the code as it's written I would say no.

associated_class = association(name).reflection.class_name.constantize

But maybe it's possible to get all polymorphic classes (classes which are commentable for instance).

drakmail commented 8 years ago

I'm created a pull request that should fix the issue (regarding to specs). Could you check gem version from github (gem 'permanent_records', github: 'drakmail/permanent_records', branch: 'polymorphic_counter_cache'?

JackDanger commented 8 years ago

@drakmail I've added you as a collaborator on permanent_records so please do what you feel is best in getting this fix merged. If we land changes on master I'll bump the version and re-publish the gem.

n-rodriguez commented 8 years ago

@drakmail : I've switched to your branch and run my tests and it works.