0

我有这些模型:

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)

?

谢谢

4

1 回答 1

0

错误在这一行:

 = check_box_tag :product_categories_ids, category.id, @product.product_categories.include?(category), :name => 'product[product_categories_ids][]'

如果我理解正确,您想检查产品类别数组是否包含给定的类别。如果是这样,你应该改变

`@product.product_categories.include?(category)` 

`@product.categories.include?(category)`
于 2013-10-29T02:04:58.230 回答