Ruby ORM多态关系,Active Record

时间:2016-12-09 22:41:13

标签: ruby-on-rails activerecord orm polymorphism many-to-many

所以我正在使用Ruby ORM并尝试理解多对多语法和多态。 这是迄今为止我的Active Record关系。

class Association < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name: "User"
end

class User < ActiveRecord::Base
  has_many :associations
  has_many :friends, through: :associations
end

当这些朋友与多个用户关联时,我似乎无法获得每个用户的朋友列表。换句话说,一些用户有朋友,这些朋友也可能有多个用户关联。

1 个答案:

答案 0 :(得分:0)

首先,这些不是多态关联。当模型可以属于许多模型时,一个使用多态关联,例如Comment模型。用户可以对帖子,图片和项目进行评论,因此Comment模型可以属于其中任何一个,因此我们使用多态关联。 Read here了解更多信息。

嗯,你要问的是Inverse Friends,这就是你如何实现它。

class User < ActiveRecord::Base
  has_many :associations
  has_many :friends, through: :associations
  has_many :inverse_associations, class_name: "Association", foreign_key: :friend_id
  has_many :inverse_friends, through: :inverse_associations, source: :user
end

class Assocation < ActiveRecord::Base
  belongs_to :user
  belogns_to :friend,    class_name: 'User'
  belongs_to :inverse_friend, class_name: 'User', foreign_key: :friend_id
end
相关问题