Ruby on Rails Tutorial (34)
Chapter 11 再読。とりあえず 11.1 節あたりから。確認入れつつ復習
ええと、app/models/user.rb に追加される以下の記述
has_many :followed_users, through: :relationships, source: :followed
これ、source な指定が必要なのは名前による類推ができないから、なのか。
ちょい整理しつつ
11.1.1 で Relationship な model を作ってます。で、rake db:migrate する前に CreateRelationships なクラスに手を入れてます。
- follower_id をインデクスに
- followed_id をインデクスに
- follower_id + followed_id もインデクスに
- これは重複を容認しないための措置
で、上のソレですがこの二つがポイントなのか (Listing 11.10)。
has_many :relationships, foreign_key: "follower_id", dependent: :destroy has_many :followed_users, through: :relationships, source: :followed
user.relationships は User#id と Relationship#follower_id で関連付いてて、その関連を使って user.followed_users がありますよ、という事か。Relationship#followed_id と User#id で関連付けてね、という事まで言えてるあたりが凄いな。
逆の関連付けについては reverse_relationships というクラスは無いので class_name という指定が入ってますね。後は上と同じか。成程。
has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy has_many :followers, through: :reverse_relationships, source: :follower
つうか前 (0.x とか 1.x とか) はこんなに簡単 (なのか?) ではなかった気もしてますが完全にその頃の記憶は忘却の彼方。
rake db:populate
11.2.1 の Listing 11.17 で lib/tasks 配下のソレを云々な方法が出てますね。