2013-07-11 4 views
3

감안할 때 나는이 다음 모델 : 나는 다음과 같은 사양을 실행하면<< 연결 일 때 counter_cache 열이 증가하지 않는 이유는 무엇입니까?

class Location < Active::Record 
    has_many :storables, foreign_key: :bin_id 
    # ... 
end 

class Storable < Active::Record 
    belongs_to :bin, class_name: :Location, counter_cache: true 
    # ... 
end 

counter_cache이 제대로 증가하지 않습니다. #1#2은 예상대로 작동하지만 #3은 작동하지 않습니다. 뭐라 구요?

describe "location storables" do 
    specify "adding a storable increments the counter cache" do 
    l = Location.create 
    l.storables_count.should == 0 #=> PASSES 

    # method 1 
    s = Storable.create(bin: l) 
    l.reload 
    l.storables_count.should == 1 #=> PASSES 

    # method 2 
    l.storables.create 
    l.reload 
    l.storables_count.should == 2 #=> PASSES 

    # method 3 
    l.storables << Storable.create 
    l.reload 
    l.storables_count.should == 3 #=> FAILS, got 2 not 3 
    end 
end 

정말 counter_cache 절반 작업에 의해 혼동하고 있습니다. 나는 구성 문제를 발견 할 수 없다.

이 프로젝트에서는 레일 3.2.12을 사용합니다. 4 도움이되지 않았다

UPDATE

업그레이드 에 레일. 또한 방법 3을 다음과 같이 변경하면 테스트가 통과됩니다.

# method 3 
l.storables << Storable.create 
puts "proxy : #{l.storables.count}" #=> 3 
puts "relation : #{Storable.count}" #=> 3 
puts "cache : #{l.storables_count}" #=> 2 

Location.reset_counters(l.id, :storables) # corrects cache 

l.reload 
l.storables_count.should == 3 #=> PASSES 

왜 자동으로 발생하지 않습니까?

+0

허용되는 대답에 대해서는''l.storables << Storable.last''와 같은 동작을 보게됩니다. 아마도 더 나빠질 것입니다. – dgilperez

답변

3

한 가지 들어, 나는 l.storables << Storable.create과 같은 것을 쓰는 것이 적절하지 않다고 생각합니다.

  1. Storable.createlocation_id 전무

  2. l.storables <<로 새로운 저장 가능한 객체를 생성 l.id에 location_id 생성 된 객체 세트를 업데이트하고, 어떻게 든를 업데이트 잊어 :이 글을 쓰는하여

    는 두 가지 문제가 발생 카운터 캐시. 새로운 저장 가능한 레코드를 삽입하기 위해 단순히 똑똑 했어야 이후

그것은, 액티브의 잘못 될 수도 있지만 실제로 두 SQL (= 뭔가를 location_id 저장 가능한 & 업데이트를 저장 가능한 세트에 삽입)를 실행했습니다. 어쨌든 나쁜 생각이고 location_id에 외래 키 제약 조건이있는 경우 첫 번째 삽입도 실패합니다.

그래서 l.storables << Storable.new에게 대신

PS를 사용 l.storables << Storable.create으로, Storable.create의 반환 값은 새로운 기록되지 않기 때문에, l이 무엇을 결정하기가 조금 어렵습니다. 어떤 경우에는 자체 카운터 캐시를 증가시켜야하며, 다른 경우에는 자체 카운터 캐시를 증가시키고 다른 사람의 카운터 캐시를 줄이거 나 필요가 없을 수도 있습니다.

+0

아레나가 이것을 이해하지 못한다. 저를 위해 문제를 좁히는 주셔서 감사합니다! 저는 'create'유스 케이스를 지원하는 이전 작업을 위해 파고 들었습니다. counter_culture 젬은 적합 할 것 같습니다. 이 테스트는 정확히이 경우를 지원하는 것으로 보입니다 (https://github.com/magnusvk/counter_culture/blob/master/spec/counter_culture_spec.rb#L12). –