ruby-on-railsruby-on-rails-4self-joincounter-cache

Error when trying to add counter_cache to a self-join rails model


class Product < ActiveRecord::Base 
    belongs_to :parent, :class_name => 'Product', :foreign_key => :parent_id
    has_many :children, :class_name => 'Product', :foreign_key => :parent_id

I am trying to add a counter cache to the :children column. I have tried the following:

belongs_to :parent, :class_name => 'Product', :foreign_key => :parent_id
has_many :children, :class_name => 'Product', :foreign_key => :parent_id, counter_cache: true

and also:

has_many :children, :class_name => 'Product', :foreign_key => :parent_id, counter_cache: :children_count

When I run Product.reset_counters(foo.id, :children)

I get the following error:

NoMethodError: undefined method `counter_cache_column' for nil:NilClass

Am I not understanding something fundamental about counter_cache or self-joins? Information about this is scarce and doesn't apply to this type of self-join.


Solution

  • the counter cash should be on the belongs to like

    class Child  < ActiveRecord::Base
      belongs_to :product, counter_cache: true
    ...
    

    not on the has many in

    class Product < ActiveRecord::Base
      belongs_to :parent, :class_name => 'Product', :foreign_key => :parent_id
      has_many :children, :class_name => 'Product', :foreign_key => :parent_id
    

    but the database column should still be on the product

    read through 4.1.2.3 at this link for more info