Monday, June 20, 2011

[Rails] activerecord caching / association problem

I've 2 models with a belongs_to / has_many relationship - e.g. Users
has_many Orders.
The problem I have seems related to activerecord caching (which I'm
not 100% clear on).

ex1 :
user = User.create
user.orders.each ... # => (no orders, as expected)
user.orders.create
user.orders.each ... # => (still no orders this time)

Changing the 2nd loop to "user.orders(true).each" fixed it, so I guess
it's related to caching.

ex2 :
user = User.create
user.orders.count # => 0
user.orders.create
user.orders.count # => 1

Strangely, this works, which seems inconsistent with the earlier
result.

Is this expected behaviour, or a bug ?
Should the cache be invalidated on order create ?
What's the recommended way to fix this ? Just remember to use (true)
sometimes, or can I fix it in the models,
so the app code doesn't need to worry about it. E.g. is it possible to
invalidate the user and order caches
when a new associated order is created ?

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate