简体   繁体   English

has_many在Rails中嵌套到许多模型

[英]has_many nested to many models in Rails

I have 4 different models in rails and there is a has_many and belongs_to association between them. 我在rails中有4种不同的模型,它们之间有has_many和belongs_to关联。 For example: 例如:

class Apple < AR::Base
  has_many :bananas
end

class Banana < AR::Base
  belongs_to :apple
  has_many :oranges
end

class Orange < AR::Base
  belongs_to :banana
  has_many :berries
end

class Berry < AR::Base
  belongs_to :orange
end 

Now, if I write, like @apple.berries , I should get the list of berries belongs to that Apple. 现在,如果我像@apple.berries这样写,我应该得到属于该Apple的浆果列表。 So how should I define this association? 那么我应该如何定义这种关联? One of my friend told me to use inverse polymorphic association. 我的一位朋友告诉我要使用逆多态关联。 I don't know whether its related to the above issue or not. 我不知道它是否与上述问题有关。

What you actually need here is has_many + through relationship. 您实际上真正需要的是has_many + through关系。 Right now, an Apple object does contain Berry objects, but Apple object doesn't contain them directly. 现在, Apple对象确实包含Berry对象,但是Apple对象不直接包含它们。 So we need to tell it explicitly like: 因此,我们需要像这样明确地告诉它:

class Apple < ActiveRecord::Base
  has_many :bananas
  has_many :berries, through: :bananas
end

class Banana < ActiveRecord::Base
  belongs_to :apple
  has_many :oranges
  has_many :berries, through: :oranges
end

Now, you can berries directly on an Apple object as well as on a Banana object. 现在,您可以将berries直接放在Apple对象以及Banana对象上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM