1

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

我的桌子是父母和孩子,可以互相成为朋友。为此,我想创建一个朋友关联表,例如父母或孩子可以与其他父母或孩子成为朋友

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

我尝试了以下方法:

朋友桌

  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

父模型

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

但是,我坚持如何定义朋友模型。关于如何在 rails 中定义这种关系的任何提示?

4

2 回答 2

3

尝试下一个关联,

儿童模型

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
于 2015-05-11T07:39:34.180 回答
0

另一种方法

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

然后,在每个朋友类型(父母、孩子、堂兄弟等)模型中,添加关系。例如,在您的父模型中

  # 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.

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

(您可能不想要依赖的销毁参数,但您应该在删除关系时删除好友记录。)

于 2015-05-11T12:36:12.797 回答