[英]Association “has_many :through” doesn't save data in Rails
I have following scheme: 我有以下方案:
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
The view: 风景:
- 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
And the update action: 以及更新动作:
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
When I try to send out the form with data, the error in the browser is: 当我尝试发送带有数据的表格时,浏览器中的错误是:
unknown attribute: product_categories_ids
Basically, I don't know how to update the update action - how to save the data from checkboxes... 基本上,我不知道如何更新更新操作-如何保存复选框中的数据...
Thank you for every advice in advance! 谢谢您提前提出建议!
You can make product_categories_ids attr_accessor in product model 您可以在产品模型中使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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.