# Controller help with :has\_many relationship

**URL:** <https://www.ruby-forum.com/t/controller-help-with-has-many-relationship/157579>\
**Category:** Rails\
**Created:** [January 13, 2009, 10:29am UTC](https://www.ruby-forum.com/t/controller-help-with-has-many-relationship/157579 "2009-01-13T10:29:02Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alfred\_Aday](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/b3f665/32.png) [@Alfred\_Aday](https://www.ruby-forum.com/u/Alfred_Aday)\
**Post date:** [January 13, 2009, 10:29am UTC](https://www.ruby-forum.com/t/controller-help-with-has-many-relationship/157579/1 "2009-01-13T10:29:02Z")

</div>

Hey,

I’m having trouble understanding how to correctly build and save an  
object  
that has a has\_many relationship. I am trying to map Products to  
Categories  
through CategoryAssignments:

Model:

class Product \< ActiveRecord::Base

> belongs\_to :product  
> end

I generated a scaffold for Products and in it I changed the view for  
“new”  
to add a select box of categories. The idea is that when you are  
creating a  
product, you can also pick what categories it belongs to.

\> \<%= f.label :category\_assignments %\>  
\> \<%= collection\_select(:category\_assignment, :category\_id, @categories, \> :id, :name, options ={:prompt =\> true}, html\_options ={:multiple =\> true, \> :size =\> 6}) %\> \>

\>

My issue is in the controller. Specifically, for “create”, I am having  
trouble building the CategoryAssignments correctly. Here is what I have  
(it’s not working).

# GET /products/new

> |category\_assignment| category\_assignment.save }  
> else  
> format.html { render :action =\> “new” }  
> format.xml { render :xml =\> [@product.errors,  
> @category\_assignment.errors], :status =\> :unprocessable\_entity }  
> end  
> end  
> end

Can someone give me some advice on the correct way of building  
CategoryAssignments?

Thanks!
