多态,has_many_and_belongs_to_many 自引用关联

Polymorphic, has_many_and_belongs_to_many self referential association

我想加入两个具有多态多对多关联的模型。

我的table是Parent和孩子,可以成为朋友。为此,我想创建一个朋友协会 table,例如 Parents or Kids 可以与其他 Parents or Kids

成为朋友

我阅读了一些教程,涵盖了 has_many、has_many through 和多态关联,但还没有任何内容可以将这两个功能混合在一起。

我尝试了以下方法:

朋友table

  t.integer :me
  t.string :me_type
  t.integer :him
  t.string :him_type

童模

class Kid < ActiveRecord::Base
  belongs_to :parent
  has_many :friends, as: :me, polymorphic: true
  belongs_to :friends, as: :you, polymorphic:true

Parent 型号

class Parent < ActiveRecord::Base
  has_many :friends, as: :me, polymorphic: true
  belongs_to :friends, as: :you, polymorphic:true

但是,我一直卡在如何定义好友模型上。 关于如何在 rails 中定义这种关系的任何提示?

尝试下一个关联,

童模

class Kid < ActiveRecord::Base
  belongs_to :parent
  has_many :my_friends,
    :as => :me,
    :class_name => "Friend"
  has_many :their_friends,
    :as => :you,
    :class_name => "Friend"
end

父模型

class Parent < ActiveRecord::Base
  has_many :my_friends,
    :as => :me,
    :class_name => "Friend"
  has_many :their_friends,
    :as => :you,
    :class_name => "Friend"
end

好友模型

class Friend < ActiveRecord::Base
  belongs_to :me,
    :polymorphic => true
  belongs_to :you,
    :polymorphic => true
end

另一种方法

class Friend < ActiveRecord::Base
  belongs_to :friendable, :polymorphic => true 
  belongs_to :parent
  belongs_to :kid
  belongs_to :...
end

然后,在每个朋友类型(parent、child、表亲等)模型中,添加关系。例如,在您的 parent 模型中

  # DB setup connection between parent and friends, 
  # Friend is polymorphic so id and type must match, 
  has_many :passive_friends, class_name:  "Friend",
                             foreign_key: "friend_id",
                             dependent:   :destroy
  # Controller setup for DB access through model
  has_many :friends, through: :passive_friends, 
                              source: :friendable,
                              source_type: 'Parent'

在你的孩子模型中

# DB setup connection between kids and friends, 
# Friend is polymorphic so id and type must match, 
has_many :passive_friends, class_name:  "Friend",
                           foreign_key: "friend_id",
                           dependent:   :destroy
# Controller setup for DB access through model
has_many :friends, through: :passive_friends, 
                           source: :friendable,
                           source_type: 'Kid'

然后你可以做

Mr. Smith has [<%= parent.friends.count.to_s %>] friends.

并且它将包括所有类型的所有朋友。

(可以不希望dependent destroy参数,但是删除关系时应该删除好友记录。)