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

以及更新操作:

  def update
    @product = Product.find(params[:id])
    #@product.attributes = {'product_categories_ids' => []}.merge(params[:product] || {})

    respond_to do |format|
      if @product.update_attributes(params[:product])
        format.html { redirect_to '/home', notice: 'Your product was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

当我尝试发送带有数据的表单时,浏览器中的错误是:

unknown attribute: product_categories_ids

基本上,我不知道如何更新更新操作 - 如何保存复选框中的数据......

提前感谢您的每一个建议!

4

1 回答 1

0

您可以在产品模型中制作 product_categories_ids attr_accessor

class Product < ActiveRecord::Base
  has_many :product_categories, :dependent => :destroy
  has_many :categories, :through => :product_categories
  attr_accessor :product_categories_ids

  before_save :assign_catagories

  private
  def assign_catagories
    product_categories_ids.each do|cid|
    self.product_categories.build(category_id: cid )
  end
end
于 2013-10-28T16:03:39.497 回答