将数据插入联结表

时间:2016-10-05 11:21:09

标签: ruby-on-rails junction-table

我正在尝试将一组数据插入到联结中。我希望能够为每个创建的新商家设置默认产品组,然后商家可以根据需要选择设置价格可用性等。

我有当前的方法定义

def add_products
  @product = Product.all
  @product.each do |product|
    @merchant = MerchantProducts.create!(product_id: product.id, merchant_id: self.id)
  end
end
我得到的问题是以下

uninitialized constant Merchant::MerchantProducts

1 个答案:

答案 0 :(得分:0)

如果没有您的型号代码,我认为您拥有拥有并属于多个关联。所以你不能直接在MerchantProducts上执行任何操作,因为那不是 Rails模型,而是productsmerchants之间的连接表所以你可以做什么是根据您的应用程序逻辑获取商家并将其分配给产品,然后保存产品

def add_products
  @product = Product.all
  @product.each do |product|
    @merchant = #logic here to fetch the merchant
    product.merchants << @merchant
    # you will need to save the product in order to create a new record
    # in the join table
  end
end

希望有所帮助

相关问题