如何检查“has_many:through”关联中的复选框?

时间:2013-10-29 01:17:50

标签: ruby-on-rails ruby checkbox has-many-through

我有这些模特:

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)

谢谢

1 个答案:

答案 0 :(得分:0)

错误在这一行:

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

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

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

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