0

github에 stores application이 있습니다. 나는 두 모델에 대한 counter_cache를 구현하려고합니다. 1. Division 모델과 2. Products 모델. 어떤 이유로 새 값을 만들 때마다 카운터 캐시 (divisions_count)가 회사 모델에 대해 자동으로 증가하지 않고 새 제품을 추가 할 때 products_count가 Divisions 모델에 대해 증가하지 않는다고 확신하지 않습니다. 부서에.카운터 캐시가 업데이트되지 않습니다 - 이유를 모르겠 음

나는 레일 3.2.11과

내 응용 프로그램이 너무 기존의 UI와 기능을 베어하시기 바랍니다에만 POC 레벨에 루비 1.9.3-p327에있어.

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

- :

PFB 모델 구조 WRT 회사, 사업부 및 제품

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"분할은 "Microsoft"- 회사에 속하지만, 그것이 "Microsoft"- 회사에 속한다는 것은 의미가 없습니다. 아니면 belongs_to이 항상 단수이며 has_many은 항상 복수형임을 기억하십시오.

부서가 여러 회사에 속해야하는 경우 "has and belong to many"또는 간단히 HABTM이라고하는 다른 연결을 사용해야합니다 ([1] 참조).

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

+0

스테판. 해결책을 알려 주시고 예를 들어 단수형과 복수형 중에서 선택할시기를 기억해 주셔서 감사드립니다. – boddhisattva

관련 문제