0

考虑一个拥有_many 产品的商店,其中有_many 意见。以下是型号:

店铺:

class Store < ActiveRecord::Base
    attr_accessible :desc, :location, :name, :phone, :status, :url

    has_many :products
    has_many :opinions, :through => :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 的 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

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

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

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

提前致谢。

4

2 回答 2

3

这看起来像一个场景,您可以使用嵌套资源路由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.
于 2012-08-18T08:58:07.380 回答
0

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

于 2012-08-17T23:41:13.027 回答