[英]Rails: Create a new entry in a model that belongs_to two other models
Consider a Store that has_many Products which have_many Opinions. 考虑一个商店,该商店有很多产品,其中有很多意见。 Here are Models:
以下是型号:
Store: 商店:
class Store < ActiveRecord::Base
attr_accessible :desc, :location, :name, :phone, :status, :url
has_many :products
has_many :opinions, :through => :products
end
Product: 产品:
class Product < ActiveRecord::Base
attr_accessible :desc, :name, :status, :url
belongs_to :store
has_many :opinions
end
finally, Opinion: 最后,意见:
class Opinion < ActiveRecord::Base
attr_accessible :content, :eval, :status
belongs_to :store
belongs_to :product
end
To create a new opinion (that belongs to a product and a store), here is the create method of OpinionsController: 要创建一个新的意见(属于产品和商店),这是OpinionsController的create方法:
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
But here is the resulted error: Can't mass-assign protected attributes: product_id
但是,这是导致的错误:
Can't mass-assign protected attributes: product_id
Question: How can I pass the product_id to the controller? 问题:如何将product_id传递给控制器?
Tell me if you need more info. 告诉我是否需要更多信息。
Thanks in advance. 提前致谢。
This looks like a scenario where you could use nested resource routing http://guides.rubyonrails.org/routing.html#nested-resources 这看起来像是您可以使用嵌套资源路由http://guides.rubyonrails.org/routing.html#nested-resources的情况
However, if you just want a quick fix in your Opinion controller you just need to omit the product_id when building the Opinion. 但是,如果您只想在Opinion控制器中快速修复,则只需在构建Opinion时省略product_id。 Something like this should work:
这样的事情应该起作用:
# 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.
意见不能有属地:store(您可以获取诸如attr_accessible
类的商店参数)。..为什么不在控制器中显示attr_accessible
行?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.