2017-06-05 41 views
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 

我正在嘗試向:children列添加計數器高速緩存。我曾嘗試以下:嘗試將counter_cache添加到自加入導軌模型時出錯

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

也:

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

當我運行Product.reset_counters(foo.id, :children)

我收到以下錯誤:

NoMethodError: undefined method `counter_cache_column' for nil:NilClass 

難道我不理解一些基本的東西關於counter_cache或self-join?有關這方面的信息很少,不適用於這種類型的自連接。

+0

只是爲了確保'foo'是Pr的一個實例oduct? –

+0

你能分享一下你的模式嗎? – stef

+0

@Michael Gorman foo是產品的一個實例,是的。 – oktober

回答

0

櫃檯現金應該在屬於喜歡

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

不上有很多

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

但數據庫列還是應該在產品

通讀4.1.2.3在這個link欲瞭解更多信息

+0

糟糕!我的意思是: 更改爲: 'belongs_to:parent,:class_name =>'Product',::foreign_key =>:parent_id,counter_cache:true \t has_many:children,:class_name =>'Product',:foreign_key =>:parent_id' 正在運行'Product.reset_counters(1,:children)' 產生此錯誤: 'ActiveRecord :: StatementInvalid:PG :: UndefinedColumn:ERROR:關係「products」的列「products_count」不存在 LINE 1:UPDATE「products」SET「products_count」= 7 WHERE「products」....' – oktober

+0

我抓到了我的真欄錯字。我在上面糾正了它。 – oktober

+0

父表是否有'counter_cache'列?如果它確實使用這個名稱而不是'true',如果它不使用,則需要在名爲'products_count'的父表中創建一個列。 –

相關問題