0

我在github上有stores application。我試圖爲兩個模型實現counter_cache,1. Divisions模型和2.產品模型。出於某種原因,我不確定計數器緩存(divisions_count)是否會在公司模型中自動增加,無論何時創建新分部,並且類似地,當我添加新產品時,對於Divisions模型,其products_count不會增加到師。計數器緩存沒有得到更新 - 不知道爲什麼

我在軌道3.2.11和1.9.3紅寶石-P327

我的應用程序只在POC水平,所以請裸與現有的用戶界面和功能。

PFB模型結構WRT公司,事業部和產品: -

company.rb

class Company < ActiveRecord::Base 
    attr_accessible :contact_no, :email_id, :fax_no, :name, :website, :divisions_count 
    has_many :divisions #just added divisions_count to attr_accessible not sure if it helps 
    has_many :products, :through => :divisions 
end 

division.rb

class Division < ActiveRecord::Base 
    attr_accessible :company_id, :name, :products_count 
#just added products_count to attr_accessible not sure if it helps 
    belongs_to :companies, :counter_cache => true 
    has_many :products 
end 

product.rb

class Product < ActiveRecord::Base 
    attr_accessible :division_id, :model, :name, :price 
    belongs_to :divisions, :counter_cache => true 
end 

如果您想引用我爲計數器緩存實現創建的遷移,可能會發現它們爲here

請讓我知道我錯過了什麼。我想這可能是一件非常愚蠢的事情。請與我一起裸露。

謝謝。

回答

0

我認爲問題在於您使用複數名稱錯誤地設置了belongs_to。切換到單數解決了這個問題,即

# pseudo diff: 

- belongs_to :companies, :counter_cache => true 
+ belongs_to :company, :counter_cache => true 

- belongs_to :divisions, :counter_cache => true 
+ belongs_to :division, :counter_cache => true 

當編輯模型/關聯時,我發現它有助於思考一個實際的實例。所以,「Windows」分區屬於「微軟」公司是有道理的,但它屬於「微軟」公司是毫無意義的。或者只記得belongs_to總是單數,has_many總是複數。

如果您需要您的部門屬於多家公司,則需要使用稱爲「擁有並屬於多個」或HABTM的不同關聯(參見[1])。

[1] http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

+0

Stefan,它工作。感謝您的解決方案和例如,幫助記住何時在單數和複數形式之間進行選擇。 – boddhisattva

相關問題