Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2891

Undefined method when using counter_cache

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.1.3
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      I'm using mongoid 3.1.2 with Ruby 2.0.0, and rails 3.2.12. When I create a new user, the counter fields fail with undefined method until their counts are updated.

      class User
        include Mongoid::Document
        include Mongoid::Timestamps
      
        field :name, type: String
        has_many :comments
      end
      
      class Comment
        include Mongoid::Document
        include Mongoid::Timestamps
       
        field :content, type: String
        belongs_to :user, counter_cache: true
      end
      
      user = User.create(name: 'Jeremy')
      user.comments_count
      #NoMethodError: undefined method `comments_count' for #<User:0x007fd64ac70d08>
      #from /Users/jeremy/.rvm/gems/ruby-2.0.0-p0@tabeso/gems/mongoid-3.1.2/lib/mongoid/attributes.rb:318:in `method_missing'
      user.comments.count #=> 0
      User.update_counters(user.id, comments_count: 0)
      user.comments_count #=> 0
      

      As a side note, setting allow_dynamic_fields: true in the mongoid.yml returns the same results.

            Assignee:
            arthurnn Arthur Nogueira Neves
            Reporter:
            jwoertink jwoertink
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: