我有3个这样的表(这只是我的表实际的简化示例):
表#1的标题为Parent,它只有两个字段:ID
和Name
。
人类有很多孩子。因此,表#2是Childs及其子parent_id
字段和其他不重要的字段。
儿童有很多朋友。表#3是Friends以及它的gotchildren_id
和其他不重要的字段。
基本上,仅parent_id
假设给定的是1,我想从Friends表中返回所有值,以使它们成为该单亲孩子的朋友。我想我会通过具有迭代儿童表,并得到所有children_id
地方parent_id
= 1,而且比我迭代通过朋友和匹配先前收集的children_id
。有人可以告诉我,有没有办法在红宝石中做到这一点。我正在使用postgresql。
采用 has_many :friends, through: :children
class Parent < ApplicationRecord
has_many :children, dependent: :destroy
has_many :friends, through: :children
end
class Child < ApplicationRecord
belongs_to :parent
has_many :friends, dependent: :destroy
end
class Friend < ApplicationRecord
belongs_to :child
end
然后,您可以像这样访问所有朋友
parent.friends
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句