Skip to content

Instantly share code, notes, and snippets.

@alekseyg
Created April 17, 2013 00:54
Show Gist options
  • Save alekseyg/5400932 to your computer and use it in GitHub Desktop.
Save alekseyg/5400932 to your computer and use it in GitHub Desktop.
This demonstrates a bug in the Rails implicit counter_cache. When creating a record with nested records via a nested form, it does not increment the {child}s_count, but when deleting via a nested form, it decrements the field.
require 'rubygems'
require 'active_record'
# Print out what version we're running
puts "Active Record #{ActiveRecord::VERSION::STRING}"
# Connect to an in-memory sqlite3 database
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => ':memory:'
)
# Create the minimal database schema necessary to reproduce the bug
ActiveRecord::Schema.define do
create_table "photos", :force => true do |t|
t.integer "posting_id"
end
create_table "postings", :force => true do |t|
t.integer "photos_count", :default => 0
end
end
# define the models
class Photo < ActiveRecord::Base
belongs_to :posting
end
class Posting < ActiveRecord::Base
has_many :photos
accepts_nested_attributes_for :photos, :allow_destroy => true
end
### Here's the bugs:
posting = Posting.create(:photos_attributes => [Photo.new.attributes])
puts "Create posting with one photo via nested form:"
puts "Posting\#photos_count: #{posting.photos_count}; Expected: 1"
posting.update_attributes(:photos_attributes => [:id => posting.photos.first.id, :_destroy => true])
puts "Delete posting's photo via nested form:"
puts "Posting\#photos_count: #{posting.photos_count}; Expected: 0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment