Skip to content

ActiveRecordError: items_count is marked as readonly

Yesterday, I was trying to add some counter caches to some of my objects, and ran into a problem. The problem is obvious now that I understand what was happening, but getting there took a while.

I couldn’t remember the syntax and everything so when I Googled rails cache counter one of the top results was the ASCIIcast Episode 23 Counter Cache Column.

The ASCIIcast said to run something like the following in the migration to populate the counter column:

Order.all.each { |o| o.update_attribute(:items_count, o.items.count) }

But it failed with this:

ActiveRecord::ActiveRecordError: items_count is marked as readonly
	from /Users/youruser/.rvm/gems/ree-1.8.7-2011.03@yourproject/gems/activerecord-3.0.12/lib/active_record/persistence.rb:121:in `update_attribute'

Sometime between the posting of the original Railscast and Rails 3.0.12, ActiveRecord started marking the counter column read only, for an obvious reason: you shouldn’t be updating it.

I modified the code to update the record without instantiating the object, like so:

Order.all.each { |o| Order.update(, :items_count => o.items.length) }

… and wouldn’t you know it, it works now.

Posted in Rails, Ruby, Software Development, Tips and Tricks.

Tagged with , , .

3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Jan says

    thank you very much… !

  2. Esteban Arango Medina says

    Why didn’t you use reset_counters?


  3. jtanium says

    I never saw that before, it’s much more elegant

Some HTML is OK

or, reply to this post via trackback.