3

I have the following models:

class Order < ActiveRecord::Base
  has_many :order_products, foreign_key: 'order_foreign_id'
  has_many :order_variation_values, through: :order_products
  accepts_nested_attributes_for :order_variation_values
end

class OrderProduct < ActiveRecord::Base
  has_many :order_variation_value
end

class OrderVariationValue < ActiveRecord::Base
  belongs_to :order_product, foreign_key: 'order_product_foreign_id'
end

When I try add record with nested_attributes I get this error:

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection (Cannot modify association 'Order#order_variation_values' because the source reflection class 'OrderVariationValue' is associated to 'OrderProduct' via :has_many.): app/controllers/api/v2/orders_controller.rb:8:in 'create'

What is wrong with the relations?

ViT-Vetal-
  • 2,431
  • 3
  • 19
  • 35

1 Answers1

3

Your association set-up is wrong. It should be

class Order < ActiveRecord::Base
  has_many :order_products, foreign_key: 'order_foreign_id'
  has_many :order_variation_values, through: :order_products
  accepts_nested_attributes_for :order_variation_values
end

class OrderProduct < ActiveRecord::Base
  belongs_to :order
  belongs_to :order_variation_value
end

class OrderVariationValue < ActiveRecord::Base
  has_many :order_products, foreign_key: 'order_foreign_id'
  has_many :orders, through: :order_products
end

See these Guides for more Info.

Pavan
  • 33,316
  • 7
  • 50
  • 76