This project is archived and is in readonly mode.

#34 ✓stale
Herryanto Siatono

attr_readonly not set when counter_cache set to true

Reported by Herryanto Siatono | April 23rd, 2008 @ 04:02 AM

Due to the class loading feature in Rails, a model class with counter_cache could be loaded before its associated class, which may cause attr_readonly for "[model]_count" field not set for its associated class.

The chances of this occuring in development environment is much higher as codes are reloaded for every request.

A simple test case to trigger this issue:

class Topic
end

class Post
  belongs_to :topic, :counter_cache => true  
end

class CounterCacheAttrReadonlyTest < Test::Unit::TestCase
  def test_attr_readonly_not_set
    Post.create :topic_id => 1
    
    # Failed, attr_readonly for posts_count in Topic not set 
    # because Topic has not been loaded and defined? returns false      
    assert_equal Set.new('posts_count'), Topic.attr_readonly 
  end
end

Attached is the patch. Thanks.

Comments and changes to this ticket

  • Michael Koziarski

    Michael Koziarski April 23rd, 2008 @ 09:15 AM

    Could you add the tests to the .patch you've attached please? Two style issues

    
    if (reflection.klass rescue nil) and reflection.klass.respond_to?(:attr_readonly)
    
    

    Why do you need the rescue there, and trailing conditionals shouldn't be that long, rewrite it to if ... end instead.

    Cheers!

  • DHH

    DHH April 29th, 2008 @ 11:20 PM

    • State changed from “new” to “incomplete”

    Change ticket status to open when fixed.

  • Rohit Arondekar

    Rohit Arondekar October 6th, 2010 @ 06:47 AM

    • State changed from “incomplete” to “stale”
    • Tag set to activerecord, patch
    • Importance changed from “” to “”

    Marking ticket as stale. If this is still an issue please leave a comment with suggested changes, creating a patch with tests, rebasing an existing patch or just confirming the issue on a latest release or master/branches.

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>

Pages