对第 12 章 Hartl 的 railstutorial 中的数据模型感到困惑

Confused about data model in Hartl's railstutorial in Chapter 12

因此,在第 12 章或 Hartl 的 Railstutorial 中,我们正在构建用户关注彼此 "twitter" 提要的能力。这被建模为用户形成关系,我们创建了一个关系模型,其中 table 具有 follower_id 和 followed_id。同样在模型中,我们将其与用户模型关联如下:

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
end

我们还将用户模型与关系模型关联如下:

class User < ActiveRecord::Base
  has_many :active_relationships,  class_name:  "Relationship",
                                   foreign_key: "follower_id",
                                   dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :following, through: :active_relationships,  source: :followed
  has_many :followers, through: :passive_relationships, source: :follower

我很困惑为什么我们需要 has_many :following 在用户模型中。教程里说follow某人是活跃关系,那为什么要说users have many active relationship,users are also following many(这是活跃关系)。 has_many :following doing that has_many :active_relationships 不能做什么?

另外我的第二个问题是为什么 belongs_to 被分成关注者和关注者,而不仅仅是用户。在用户身上使用两个 belongs_to 而不是一个,我们有什么好处?

这是一种访问 Users 的方法,这些 Users 是特定用户关注或被关注的,而不是关系。

如果您只有 @user.active_relationships,那将 return 支持联接 table 中的关系。但是使用 @user.following 你会得到一个 User 对象的关联数组。

关于你的第二个问题,两个用户之间的关系需要 2 个对象而不是一个,并且只有一个 belongs_to :user.

是没有意义的

Ruby on Rails Guides - Associations | Has many :through