Ruby on Rails Tutorial 学习笔记 --第十一章关注用户

1.为了得到一个由所有被关注用户组成的 followed_users 数组,我们可以先获取由 followed_id 属性组成的数组,再查找每个用户。不过,如你所想,Rails 为我们提供了一种更简单的方式,那就是 has_many through

[ruby]  view plain copy
  1. 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: :destroy

6.




7.




8.


9.


10.


11.



12.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值