# Information about query caching and HM through

**URL:** <https://www.ruby-forum.com/t/information-about-query-caching-and-hm-through/130910>\
**Category:** Rails\
**Created:** [March 4, 2008, 12:28pm UTC](https://www.ruby-forum.com/t/information-about-query-caching-and-hm-through/130910 "2008-03-04T12:28:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jub](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/f9ae1b/32.png) [@jub](https://www.ruby-forum.com/u/jub)\
**Post date:** [March 4, 2008, 12:28pm UTC](https://www.ruby-forum.com/t/information-about-query-caching-and-hm-through/130910/1 "2008-03-04T12:28:47Z")

</div>

Hi there,

I would like to find more information about query caching, or about the  
concept behind the following behavior, in a “User has many Groups  
through Memberships” association.  
Let me show you an example.

# Base :

user = User.find\_by\_email(‘removed\_email\_address@domain.invalid’)  
group = List.create( :title =\> “First group” )  
group2 = List.create( :title =\> “Second group” )

# if I do this :

Membership.create(:group =\> group, :user =\> user)  
Membership.create(:group =\> group2, :user =\> user)

user.groups.each do |g| puts g.title end

# the result is as expected

First group  
Second group

# But if do this :

Membership.create(:group =\> group, :user =\> user)  
user.groups.each do |g| puts g.title end  
Membership.create(:group =\> group2, :user =\> user)  
user.groups.each do |g| puts g.title end

# the result is :

First group  
First group

# instead of

First group  
First group  
Second group

What’s the magic behind that ?  
Also, what’s the best way to create new memberships and avoid troubles ?

Thanks

---

<div class="post-metadata">

**Author:** ![jub](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/f9ae1b/32.png) [@jub](https://www.ruby-forum.com/u/jub)\
**Post date:** [March 4, 2008, 12:46pm UTC](https://www.ruby-forum.com/t/information-about-query-caching-and-hm-through/130910/2 "2008-03-04T12:46:05Z")

</div>

On 4 Mar 2008, at 11:28, aJo aJo wrote:

> 

This isn’t a query caching problem, it’s activerecord’s association  
caching (so if you were to add a user.reload or a user.groups.reload  
in there you would get the right answer)

Fred

---

<div class="post-metadata">

**Author:** ![jub](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/f9ae1b/32.png) [@jub](https://www.ruby-forum.com/u/jub)\
**Post date:** [March 4, 2008, 1:03pm UTC](https://www.ruby-forum.com/t/information-about-query-caching-and-hm-through/130910/3 "2008-03-04T13:03:21Z")

</div>

OK, I indeed found that a .reload could do the trick.

But I suppose we are not condemned to do a .reload before every call to  
an association, so how do you avoid that ?
