Multiple habtm problem


#1

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]

<% for color in @colors%> checked="checked"<%end%> /> <%= color.name %> <% end %>

<% for size in @sizes%> checked="checked"<%end%> /> <%= size.name %> <% end %>

[/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.


#2

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