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
>  has_many :category_assignments
>  ...
> end
>
> class Category < ActiveRecord::Base
>  has_many :category_assignments
> end
>
> class CategoryAssignment < ActiveRecord::Base
>  belongs_to :category
>  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
>   # GET /products/new.xml
>   def new
>     @product = Product.new
>     @categories = Category.find(:all)
>
>     respond_to do |format|
>       format.html # new.html.erb
>       format.xml  { render :xml => @product }
>     end
>   end
>
>   # POST /products
>   # POST /products.xml
>   def create
>     @product = Product.new(params[:product])
>     logger.info("New Product looks like #{params[:product]}\n");
>     logger.info("New Category Assignment looks like
> #{params[:category_assignment]}\n");
>
>     respond_to do |format|
>       if @product.save #and @category_assignment.each {
> |category_assignment| category_assignment.save }
>         @category_assignments =
> @product.category_assignments.build(params[:category_assignment])
>         @category_assignments.save
>         logger.info("Category Assignment ARRAY ==
> @category_assignments\n");
>
>         flash[:notice] = 'Product was successfully created.'
>         format.html { redirect_to(@product) }
>         format.xml  { render :xml => @product, :status => :created,
> :location => @product }
>       else
>         format.html { render :action => "new" }
>         format.xml  { render :xml => [[email protected],
> @category_assignment.errors], :status => :unprocessable_entity }
>       end
>     end
>   end


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

Thanks!

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to