保存用户产品时如何将当前用户添加到 user_product 表。
我在网上查看了一些信息,表明我可以将参数传递给构建方法,但这不起作用。错误消息是“无法批量分配受保护的属性:user_id”
产品控制器:
定义新
@product = Product.new
@product.user_products.build(:user_id => current_user)
respond_to do |format|
format.html # new.html.erb
format.json { render json: @product }
end
结尾
我的模型是:Product
, User
,User_Product
类产品 < ActiveRecord::Base
attr_accessible :name, :issn, :category, :user_products_attributes
validates_presence_of :name, :issn, :category
validates_numericality_of :issn, :message => "has to be a number"
has_many :user_products
has_many :users, :through => :user_products
accepts_nested_attributes_for :user_products
end
class UserProduct < ActiveRecord::Base
attr_accessible :price
validates_presence_of :price
validates_numericality_of :price, :message => "has to be a number"
belongs_to :user
belongs_to :product
end
class user < ActiveRecord::Base
# devise authentication here
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :user_products, :dependent => :destroy
has_many :products, :through => :user_products
end