Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is counter_cache column not increasing when << an association?
    primarykey
    data
    text
    <p>Given I have the following models:</p> <pre><code>class Location &lt; Active::Record has_many :storables, foreign_key: :bin_id # ... end class Storable &lt; Active::Record belongs_to :bin, class_name: :Location, counter_cache: true # ... end </code></pre> <p>When I run the following spec, the <code>counter_cache</code> doesn't increment correctly. Method <code>#1</code> and <code>#2</code> work as expected, but NOT <code>#3</code>. What gives?</p> <pre><code>describe "location storables" do specify "adding a storable increments the counter cache" do l = Location.create l.storables_count.should == 0 #=&gt; PASSES # method 1 s = Storable.create(bin: l) l.reload l.storables_count.should == 1 #=&gt; PASSES # method 2 l.storables.create l.reload l.storables_count.should == 2 #=&gt; PASSES # method 3 l.storables &lt;&lt; Storable.create l.reload l.storables_count.should == 3 #=&gt; FAILS, got 2 not 3 end end </code></pre> <p>I'm really confused by the <strong>counter_cache half working</strong>. I can't spot a configuration problem either.</p> <p>Using <strong>Rails 3.2.12</strong> on this project.</p> <p><strong>UPDATE</strong></p> <p>Upgrading to <strong>rails 4</strong> didn't help. Also, if I change method #3 to the following, the test passes:</p> <pre><code># method 3 l.storables &lt;&lt; Storable.create puts "proxy : #{l.storables.count}" #=&gt; 3 puts "relation : #{Storable.count}" #=&gt; 3 puts "cache : #{l.storables_count}" #=&gt; 2 Location.reset_counters(l.id, :storables) # corrects cache l.reload l.storables_count.should == 3 #=&gt; PASSES </code></pre> <p>Why isn't this happening automatically?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload