【问题标题】:Counter cache doesn't get updated - not sure why计数器缓存未更新 - 不知道为什么
【发布时间】:2013-08-04 10:08:21
【问题描述】:

我在 github 上有一个 stores application。我正在尝试为两个模型实现 counter_cache,1. Divisions 模型和 2. Products 模型。出于某种原因,我不确定每当我创建一个新的 Division 时,Company 模型的计数器缓存(divisions_count)不会自动增加,同样,当我添加新产品时, Products_count 不会为 Divisions 模型增加到部门。

我在 rails 3.2.11 和 ruby​​ 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

【问题讨论】:

    标签: ruby-on-rails-3 performance has-many-through has-many counter-cache


    【解决方案1】:

    我认为问题在于您使用复数名称错误地设置了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

    【讨论】:

    • 斯特凡,它成功了。感谢您的解决方案和例如,帮助记住何时在单数和复数形式之间进行选择。
    猜你喜欢
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 2022-01-17
    • 2013-12-05
    • 2013-05-30
    • 2019-01-05
    相关资源
    最近更新 更多