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

oktober
  • 153
  • 2
  • 8

1 Answers1

1

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

Michael Gorman
  • 1,077
  • 7
  • 13
  • oops! I meant this: Changing it to this: `belongs_to :parent, :class_name => 'Product', :foreign_key => :parent_id, counter_cache: true has_many :children, :class_name => 'Product', :foreign_key => :parent_id` And running `Product.reset_counters(1, :children)` Yields this error: `ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "products_count" of relation "products" does not exist LINE 1: UPDATE "products" SET "products_count" = 7 WHERE "products"....` – oktober Jun 05 '17 at 16:47
  • I caught my :true column typo. I corrected it above. – oktober Jun 05 '17 at 16:48
  • does the parent table have a column for the `counter_cache`? if it does use that name instead of `true`, if it doesn't you will need to a column in the parent table that is named `products_count` – Michael Gorman Jun 05 '17 at 16:50
  • Thank you. Yes, I was confusing myself with the self-join issue. [This article helped also](http://ryan.mcgeary.org/2016/02/05/proper-counter-cache-migrations-in-rails/). Having added the correct column, I am able to run the update. – oktober Jun 05 '17 at 17:10