This project is archived and is in readonly mode.

#3954 ✓stale
bdtomlin

counter_cache fails silently in rails 3

Reported by bdtomlin | February 14th, 2010 @ 12:31 AM

Here is the code for the simplest possible implementation:

  rails g model Collection name:string collectibles_count:integer
  rails g model Collectible name:string collection:references

edit the CreateCollections migration for default value

  t.integer :collectibles_count, :default => 0

The model code

  class Collection < ActiveRecord::Base
    has_many :collectibles
  end

  class Collectible < ActiveRecord::Base
    belongs_to :collection, :counter_cache => true
  end

and in the rails console...

  collection = Collection.create(:name => 'collection name')
  => #<Collection id: 2, name: "collection name", collectibles_count: 0, created_at: "2010-02-14 00:20:40", updated_at: "2010-02-14 00:20:40">


collectible = Collectible.create(:name => 'collectible name') => #<Collectible id: 3, name: "collectible name", collection_id: nil, created_at: "2010-02-14 00:21:16", updated_at: "2010-02-14 00:21:16">


collection.collectibles << collectible => [#<Collectible id: 3, name: "collectible name", collection_id: 2, created_at: "2010-02-14 00:21:16", updated_at: "2010-02-14 00:21:52">]


collection => #<Collection id: 2, name: "collection name", collectibles_count: 0, created_at: "2010-02-14 00:20:40", updated_at: "2010-02-14 00:20:40">


collection.collectibles.create(:name => 'another collectible') => #<Collectible id: 4, name: "another collectible", collection_id: 2, created_at: "2010-02-14 00:22:40", updated_at: "2010-02-14 00:22:40">


collection => #<Collection id: 2, name: "collection name", collectibles_count: 0, created_at: "2010-02-14 00:20:40", updated_at: "2010-02-14 00:20:40">

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Pages