Association with the same model

时间:2017-12-18 07:11:51

标签: ruby-on-rails database associations mongoid

I have two models 'Product' and 'Variant',product has many variants,now I have to set assocaiation of a new Model named as "Ingridient" with variant in such a way that Variant has many ingridients.but in ingridents I want to show that it again has_one product and variant.for example

 class Variant
  has_many :ingridients
  belongs_to :product
end

class Ingridient
 belongs_to :variant
 belongs_to :product
end

now in my ingrident model I also want has_one variant and has_one product at the same time.how should I set my associations.I know multiple association with same table but dont know how to implement it in my app.Iam using mongoid as my database.

Edit : Actually in my flow User can create a Product with many variants and then each variant can have multiple ingridients.In that each ingrident i have select box for selecting products and variants form database .means ingridients will consist a product a variant ,quantity etc fields .To make it more clear Iam making a Recipe .

1 个答案:

答案 0 :(得分:0)

我不是100%明确你想做什么。

但它看起来像是想要一个不同名称的关联。

class Variant
  has_many :ingridients, :foreign_key => 'FieldName', :class_name => 'CassName'
  belongs_to :product, :foreign_key => 'FieldName', :class_name => "CassName"
end

class Ingridient
 belongs_to :variant, :foreign_key => 'FieldName', :class_name => "CassName"
 belongs_to :product, :foreign_key => 'FieldName', :class_name => "CassName"
end

我希望这有助于