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

时间:2012-08-17 21:51:09

标签: ruby-on-rails model-associations mass-assignment

考虑一个has_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的创建方法:

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传递给控制器​​?

告诉我您是否需要更多信息。

提前致谢。

2 个答案:

答案 0 :(得分:3)

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

的场景

但是,如果您只想快速修复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.

答案 1 :(得分:0)

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