Don't work when we assign parent model to children.
Closed this issue · 3 comments
rjurado01 commented
Hi, I have the next problem:
class Library
include Mongoid::Document
field :name
field :city
field :book_count
has_many :books
end
class Book
include Mongoid::Document
include Mongoid::MagicCounterCache
field :first
field :last
belongs_to :library
counter_cache :library
end
> library = Library.create
=> #<Library _id: 53271d5a7cf9782c8b000005, name: nil, city: nil, book_count: nil>
> book = Book.create
=> #<Book _id: 53271d6d7cf9782c8b000006, first: nil, last: nil, library_id: nil>
> book.library = library
=> #<Library _id: 53271d5a7cf9782c8b000005, name: nil, city: nil, book_count: nil>
> book.save
=> true
> library.reload.book_count
=> nil
How you can see, the library book_count don't be updated when we assign the library to book. This is a bug ?
Thanks.
jah2488 commented
Have you tried creating the book with this syntax?
library = Library.create
library.books.create
library.book_count
#=> 1
The gem updates the counter when associated objects are created or destroyed, but not when they are associated. So this isn't entirely a bug, but I can see why this would be unexpected.
In the end. Its not a running count that is dynamically maintained, but instead a static number that is updated in the create lifecycle.
rjurado01 commented
Ok, thanks for the clarification, but I need that it works with associations.