Forum: Ruby on Rails multiple habtm problem

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.
arudgick (Guest)
on 2005-12-09 04:49
(Received via mailing list)
here it goes...

i am creating an online store for tshirts. i have seperate tables for
shirts, colors, sizes, and corresponding join tables. in all three of my
models i have set up habtm relationships.

my view looks like this...

[code excerpt]
<p>
<% for color in @colors%>
<input type='checkbox' name='shirt[color_ids][]' value='<%= color.id %>'
<%if @shirt.colors.include? color%>checked="checked"<%end%> />
<%= color.name %>
<% end %>
</p>

<p>
<% for size in @sizes%>
<input type='checkbox' name='shirt[size_ids][]' value='<%= size.id %>'
<%if
@shirt.sizes.include? size%>checked="checked"<%end%> />
<%= size.name %>
<% end %>
</p>
[/code excerpt]

the 'create' form only inserts info for one of the habtm relationships,
but
the 'update/edit' form will insert both.

here's my shirt controller

[code excerpt]
  def new
    @shirt = Shirt.new
    @sizes =  Size.find_all
    @colors = Color.find_all
  end

  def create
    @shirt = Shirt.new(params[:shirt])
    if @shirt.save
      flash[:notice] = 'Shirt was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @shirt = Shirt.find(params[:id])
    @sizes =  Size.find_all
    @colors = Color.find_all
  end

  def update
    @shirt = Shirt.find(params[:id])

    #added the following 3 lines
    if !params['shirt']['size_ids']
      @shirt.sizes.clear
    end

    #and these 3 lines
    if !params['shirt']['color_ids']
      @shirt.colors.clear
    end

    if @shirt.update_attributes(params[:shirt])
      flash[:notice] = 'Shirt was successfully updated.'
      redirect_to :action => 'show', :id => @shirt
    else
      render :action => 'edit'
    end
  end
[/code excerpt]

i'm banging my head against the wall trying to figure out this seemingly
simple problem.
ara.t.howard (Guest)
on 2005-12-09 05:13
(Received via mailing list)
On Thu, 8 Dec 2005, Anthony Rudgick wrote:

>  end
>
>  def create
>    @shirt = Shirt.new(params[:shirt])

i think you want to do something like

   @shirt.colors << Color.find_all
   @shirt.sizes << Size.find_all

here

??

-a
This topic is locked and can not be replied to.