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 ?
on 2011-06-21 13:12
on 2011-06-21 16:16
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