Forum: Ruby on Rails activerecord caching / association problem

8fd7f55e758ada69bd967394ef9c26e5?d=identicon&s=25 sreid (Guest)
on 2011-06-21 11:12
(Received via mailing list)
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 ?
Bf33b52d4c4c894a064207eca372b42a?d=identicon&s=25 Chirag Singhal (Guest)
on 2011-06-21 14:16
(Received via mailing list)
It is not inconsistent behavior.
user.orders.count will fire a count query on your database and will
return
the result. You can check your log to verify this.
If you use 'size' instead of 'count', then it will should give you 0
both
the times.

This may not be the best solution, but you can probably do this:
user.orders << Order.create
instead of user.orders.create
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.