我有这些模型:
class Category < ActiveRecord::Base
has_many :product_categories, :dependent => :destroy
has_many :product, :through => :product_categories
end
class Product < ActiveRecord::Base
has_many :product_categories, :dependent => :destroy
has_many :categories, :through => :product_categories
end
class ProductCategory < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
风景:
- Category.order('title').each do |category|
= check_box_tag :product_categories_ids, category.id, @product.product_categories.include?(category), :name => 'product[product_categories_ids][]'
= label_tag :product_categories_ids, category.title
当我打印出来时@product.product_categories
:
= @product.product_categories.inspect
输出是:
[#<ProductCategory id: 5, product_id: 9, category_id: 9, created_at: "2013-10-29 01:06:54", updated_at: "2013-10-29 01:06:54">, #<ProductCategory id: 6, product_id: 9, category_id: 7, created_at: "2013-10-29 01:06:54", updated_at: "2013-10-29 01:06:54">]
我认为这就是此处未选中各个复选框的原因:
= check_box_tag :product_categories_ids, category.id, @product.product_categories.include?(category), :name => 'product[product_categories_ids][]'
如何更新此部分,检查是否应选中所有复选框:
@product.product_categories.include?(category)
?
谢谢