0

I am trying to insert a set of data into a junction. I want to be able to set the default set of products to every new merchant that is created, then the merchant will have options to set their prices availability etc based on their needs.

I have the current method define

def add_products
  @product = Product.all
  @product.each do |product|
    @merchant = MerchantProducts.create!(product_id: product.id, merchant_id: self.id)
  end
end

problem I am getting is the below

uninitialized constant Merchant::MerchantProducts
Pavan
  • 33,316
  • 7
  • 50
  • 76
Boss Nass
  • 3,384
  • 9
  • 48
  • 90
  • try with `def add_products @product = Product.all @product.each do |product| @merchant = ::MerchantProducts.create!(product_id: product.id, merchant_id: self.id) end end` (even though there is no need to assign `@merchant` value here) – Andrey Deineko Oct 05 '16 at 11:26

1 Answers1

0

Without your model codes, I assume you have a Has And Belongs To Many Association. so you cant directly perform any operations on MerchantProducts since thats not a Rails Model, instead it is a join table between products and merchants so what you could do is fetch the merchant as per your application logic and assign it to product like and then save the product

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

Hope it helps

Sajan
  • 1,893
  • 2
  • 19
  • 39