JackDanger/permanent_records

Counter cache doesn't work with polymorphic association

n-rodriguez opened this issue · 6 comments

It breaks here with NameError: uninitialized constant Commentable

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

Oh, I'll fix it tomorrow

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).

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'?

@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.

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