我想加入两个具有多对多关联性的模型。
我的桌子是父母和孩子,可以成为彼此的朋友。要实现这一点,我想创建一个朋友关联表,如父母或孩子可以成为其他父母或孩子的朋友
我阅读了一些教程,涵盖了has_many,has_many和多态关联,但还没有任何内容可以将这两个特性混合在一起。
我尝试了以下内容:
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中定义此关系的任何提示?
答案 0 :(得分:2)
尝试下一个关联,
孩子模特
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
答案 1 :(得分: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.
它将包括所有类型的所有朋友。
(您可能不需要依赖的destroy param,但删除关系时应删除好友记录。)