# Adding items to a collection associated w/ has\_many :through

**URL:** <https://www.ruby-forum.com/t/adding-items-to-a-collection-associated-w-has-many-through/113894>\
**Category:** Rails\
**Created:** [September 5, 2007, 11:22pm UTC](https://www.ruby-forum.com/t/adding-items-to-a-collection-associated-w-has-many-through/113894 "2007-09-05T23:22:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [September 5, 2007, 11:22pm UTC](https://www.ruby-forum.com/t/adding-items-to-a-collection-associated-w-has-many-through/113894/1 "2007-09-05T23:22:03Z")

</div>

All,

Quick review on has\_many :through behavior.

I have the following model setup. X and Z are related many-to-many via  
a bi-directional has\_many :through relationship (Y is the join model).

X has\_many Y  
X has many Z :through =\> Y

Y belongs\_to X  
Y belongs\_to Z

Z has\_many Y  
Z has\_many X :through =\> Y

Note that non-standard foreign key names are used between both (X and Y)  
and (Y and Z).

If I have an AR instance of a X and a Z (say @x and @new\_z), shouldn’t I  
just be able to do

@x.zs \<\< @new\_z and the appropriate record in Y should be created to  
link them?

I always seem to have to do this instead to get this to work:

@x.ys.create(:z\_identifier =\> @new\_z).

I feel like the first statement is much clearer (“add a new z to x’s  
collection of z’s”) instead of (“create a new x-z mapping record”).

Thanks,  
Wes
