Forum: Ruby on Rails Controller help with :has_many relationship

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alfred Aday (Guest)
on 2009-01-13 11:29
(Received via mailing list)
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.

  <p>
>     <%= f.label :category_assignments %><br />
>     <%= collection_select(:category_assignment, :category_id, @categories,
> :id, :name, options ={:prompt => true}, html_options ={:multiple => true,
> :size => 6}) %>
>   </p>
>

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!
This topic is locked and can not be replied to.