# Relation through

**URL:** <https://www.ruby-forum.com/t/relation-through/83205>\
**Category:** FR\
**Created:** [January 24, 2007, 10:08am UTC](https://www.ruby-forum.com/t/relation-through/83205 "2007-01-24T10:08:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![juba](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/5daacb/32.png) [@juba](https://www.ruby-forum.com/u/juba)\
**Post date:** [January 24, 2007, 10:08am UTC](https://www.ruby-forum.com/t/relation-through/83205/1 "2007-01-24T10:08:57Z")

</div>

Bonjour,

J’ai une relation has\_many entre deux modÃ¨les User et Network via un  
modÃ¨le intermÃ©diaire (utilisation via :through) UserNetwork.

Lorsque je fais mes tests unitaires, initialement je teste sans aucune  
relation entre deux modÃ¨les, puis j’en ajoute en crÃ©ant des instances de  
la table intermÃ©diaire (c’est peut-Ãªtre lÃ le problÃ¨me). Le problÃ¨me est  
que le cache est effectif et aucune relation n’est chargÃ©e, Ã moins que  
je force le rechargement.

L’appel de @user1.user\_networks renvoie vide (ok)

un= UserNetwork.new  
un.user = @user1  
un.network = net1  
un.save!

et l’appel de :

@user1.user\_networks renvoie [] (KO)  
@user1.user\_networks(true) [un] (ok)

Dois-je faire cela pour Ãªtre sÃ»r :

net1.user\_networks \<\< un  
@user1.user\_networks \<\< un

Pouvez-vous me dire comment vous gÃ©rer cela ?

Merci,

Julien

---

<div class="post-metadata">

**Author:** ![juba](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/5daacb/32.png) [@juba](https://www.ruby-forum.com/u/juba)\
**Post date:** [January 24, 2007, 5:17pm UTC](https://www.ruby-forum.com/t/relation-through/83205/2 "2007-01-24T17:17:40Z")

</div>

Le problÃ¨me rencontrÃ© :

[http://blog.hasmanythrough.com/2006/04/17/join-models-not-proxy-collections](http://blog.hasmanythrough.com/2006/04/17/join-models-not-proxy-collections)

Une solution Ã©lÃ©gante :  
[has\_many :through - New on edge: Magic join model creation](http://blog.hasmanythrough.com/2006/8/19/magic-join-model-creation)

Du coup je fais :  
@user1.networks.push\_with\_attributes( net1, :champ =\> ‘valeur’ )

Avec :

class User \< ActiveRecord::Base  
has\_many :user\_networks  
has\_many :networks, :through =\> :user\_network do  
def push\_with\_attributes( network, join\_attrs = {} )  
UserNetworkPrivacy.with\_scope( :create =\> join\_attrs ) { self \<\<  
network }  
end  
end  
…

end
