rails - habtm关联不保存到数据库

时间:2011-10-03 17:35:20

标签: ruby-on-rails associations has-and-belongs-to-many nested-attributes

产品总监:

def update
 params[:product][:category_ids] ||= []
 @product = Product.find(params[:id])
 if @product.update_attributes(params[:product])
  redirect_to @product
 else
  render "edit"
 end 

形式:

    <% for category in Category.all %>
    <%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %> 
    <%= category.name %>
  <% end %> 

当我查看日志时,看起来它更新了类别,但是当我转到rails控制台并对产品进行查找时,它告诉我category_id为零,所以当我搜索所有产品时在某个产品类别中,它不会返回任何内容,因为所有category_id都是nil。

我有products_products的产品和类别模型以及简单的连接表。我尝试在产品模型中使用accepts_nested_attributes_for并进行相应的表单更改,但也无法正常工作。

有谁知道它为什么不保存到数据库级别?同样在这种情况下,以我在这里的方式或嵌套属性的方式做得更好吗?感谢。

更新

日志代码

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

产品型号代码

attr_accessible :name, :manufacturer, :price, :category_ids, :image, :remote_image_url, :available
has_and_belongs_to_many :categories

来自类别模型的代码

has_and_belongs_to_many :products

1 个答案:

答案 0 :(得分:0)

我认为你无法用“habtm”来完成你想做的事情。请查看the answer to this question关于将habtm更改为has_many :through关联,并使用表单中的连接表模型更新关联。