关联“has_many:through”不会在Rails中保存数据

时间:2013-10-28 15:58:58

标签: ruby-on-rails ruby associations 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

更新操作:

  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

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

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

1 个答案:

答案 0 :(得分: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