現在rails-tutorialで14章のフォロー機能のモデリングを勉強しているのですが
user.rb
has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed
relationship.rb
belongs_to :followed, class_name: "User"
以上のコードで
>> user1=User.first >> user1.active_relationships Relationship Load (0.2ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = ? LIMIT ? [["follower_id", 1], ["LIMIT", 11]] => #<ActiveRecord::Associations::CollectionProxy [#<Relationship id: 1, follower_id: 1, followed_id: 2, created_at: "2020-04-14 05:44:34", updated_at: "2020-04-14 05:44:34">]>
としたとき、user1.active_relationshipsはfollower_idを外部キーとしたときのRelationshipの配列を生成しているのはわかるのですが、user.followingが
>> user1.following User Load (0.3ms) SELECT "users".* FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower_id" = ? LIMIT ? [["follower_id", 1], ["LIMIT", 11]] => #<ActiveRecord::Associations::CollectionProxy [#<User id: 2, name: "Zachariah Reichert", email: "example-1@railstutorial.org", created_at: "2020-04-12 05:10:29", updated_at: "2020-04-12 05:10:29", password_digest: "$2a$10$HbKR88mEDs5xpPinCE62gOwO8TljGLR..2vW6ZoREJT...", remember_digest: nil, admin: false, activation_digest: "$2a$10$gLpEHFPTMMemeQXg/9KSbe1bLLQdEEnkU8Jw8LfcDFQ...", activated: true, activated_at: "2020-04-12 05:10:29", reset_digest: nil, reset_sent_at: nil>]>
というような結果に何故なるのかが分かりません。followingはactive_relationshipsの後にbelongs_toをどう解釈して以上の結果を出しているのでしょうか?
ややこしく読みづらいとは思うのですがご教授お願い致します。
あなたの回答
tips
プレビュー