Product controller:
def update
params[:product][:category_ids] ||= []
@product = Product.find(params[:id])
if @product.update_attributes(params[:product])
redirect_to @product
else
render "edit"
end
form:
<% for category in Category.all %>
<%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %>
<%= category.name %>
<% end %>
When I look at the log, it looks like it updated the category, but when I go to rails console and did a lookup for the product, it tells me that the category_id is nil so when I do a search for all products in a certain product category, it doesn't return anything because all the category_id is nil.
I have a product and a category model and a simple join table for categories_products. I tried using accepts_nested_attributes_for in the product model and made the respective form changes as well and that didn't work either.
Does anyone know why it doesn't save to the database level? Also in a situation like this, is it better to do it the way I have it here or to do nested attributes? Thanks.
UPDATE
Code from log
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx", "product"=>{"remote_image_url"=>"", "name"=>"Test", "manufacturer"=>"Unknown", "category_ids"=>["1"], "price"=>"$25.00", "available"=>"true", "commit"=>"Update", "id"=>"1"}
Category Load (0.5ms) SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 1 LIMIT 1
Category Load (0.2ms) SELECT * FROM `categories` INNER JOIN `categories_products` ON `categories`.id = `categories_products`.category_id WHERE (`categories_products`.product_id = 1 )
AREL (0.4ms) DELETE FROM `categories_products` WHERE `categories_products`.`product_id` = 1 AND `categories_products`.`category_id` IN (2)
AREL (0.4ms) UPDATE `products` SET `price` = 0.0, `updated_at` = '2011-10-03 16:48:01' WHERE `products`.`id` = 1
SQL (1.8ms) COMMIT
Code from product model
attr_accessible :name, :manufacturer, :price, :category_ids, :image, :remote_image_url, :available
has_and_belongs_to_many :categories
Code from category model
has_and_belongs_to_many :products