Rails:在属于其他两个模型的模型中创建一个新条目

考虑一个has_many产品的商店,其中有很多意见。 这是模特:

商店:

class Store  :products end 

产品:

 class Product < ActiveRecord::Base attr_accessible :desc, :name, :status, :url belongs_to :store has_many :opinions end 

最后,意见:

 class Opinion < ActiveRecord::Base attr_accessible :content, :eval, :status belongs_to :store belongs_to :product end 

要创建新的意见(属于产品和商店),这里是OpinionsController的创建方法:

 def create # Get product info. product = Product.find_by_id params[:opinion][:product_id] # Create a new opinion to this product opinion = product.opinions.build params[:opinion] opinion.status = 'ON' if opinion.save redirect_to :back, :notice => 'success' else redirect_to :back, :alert => 'failure' end end 

但这是产生的错误: Can't mass-assign protected attributes: product_id

问题:如何将product_id传递给控制器​​?

如果您需要更多信息,请告诉我。

提前致谢。

这看起来像是一个可以使用嵌套资源路由的场景http://guides.rubyonrails.org/routing.html#nested-resources

但是,如果您只想快速修复Opinion控制器,则只需在构建Opinion时省略product_id。 像这样的东西应该工作:

 # Get product info. product = Product.find_by_id params[:opinion].delete(:product_id) # delete removes and returns the product id # Create a new opinion to this product opinion = product.opinions.build params[:opinion] # Since there is no product id anymore, this should not cause a mass assignment error. 

意见不能拥有belongs_to:store(你可以获得像attr_accessible这样的商店参数)所以..为什么你没有在你的控制器中显示attr_accessible线?