Ruby on Rails-从孙子表中获取记录

吉姆

我有3个这样的表(这只是我的表实际的简化示例):

表#1的标题为Parent,它只有两个字段:IDName

人类有很多孩子。因此,表#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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章