# activerecord caching / association problem

**URL:** <https://discuss.rubyonrails.org/t/activerecord-caching-association-problem/59547>\
**Category:** rubyonrails-talk\
**Created:** [June 20, 2011, 9:59pm UTC](https://discuss.rubyonrails.org/t/activerecord-caching-association-problem/59547 "2011-06-20T21:59:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sreid](https://avatars.discourse-cdn.com/v4/letter/s/58956e/32.png) [@sreid](https://discuss.rubyonrails.org/u/sreid)\
**Post date:** [June 20, 2011, 9:59pm UTC](https://discuss.rubyonrails.org/t/activerecord-caching-association-problem/59547/1 "2011-06-20T21:59:10Z")

</div>

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 ?

---

<div class="post-metadata">

**Author:** ![Chirag](https://avatars.discourse-cdn.com/v4/letter/c/ecccb3/32.png) [@Chirag](https://discuss.rubyonrails.org/u/Chirag)\
**Post date:** [June 21, 2011, 12:15pm UTC](https://discuss.rubyonrails.org/t/activerecord-caching-association-problem/59547/2 "2011-06-21T12:15:05Z")

</div>

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
