1.为了得到一个由所有被关注用户组成的 followed_users
数组,我们可以先获取由 followed_id
属性组成的数组,再查找每个用户。不过,如你所想,Rails 为我们提供了一种更简单的方式,那就是 has_many through
。
- has_many :followed_users, through: :relationships, source: "followed_id"
2.这种连接两个数据表的 id,我们称之为外键(foreign key),当指向 User 模型的外键为 user_id
时,Rails 就会自动的获知关联关系,因为默认情况下,Rails 会寻找 <class>_id
形式的外键,其中 <class>
是模型类名的小写形式。
3.
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many :relationships, foreign_key: "follower_id", dependent: :destroy has_many :followed_users, through: :relationships, source: :followed
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
4.
resources :users do
member do
get :following, :followers
end
end
.
5.
当指向 User 模型的外键为
user_id
时,Rails 就会自动的获知关联关系,因为默认情况下,Rails 会寻找<class>_id
形式的外键,其中<class>
是模型类名的小写形式。5现在,尽管我们处理的还是用户,但外键是follower_id
了,所以我们要告诉 Rails 这一变化,如代码 11.4 所示。has_many :relationships, foreign_key: "follower_id", dependent: :destroy6.
7.
8.
9.
10.
11.
12.