railsで友達機能について質問があるのですが
https://qiita.com/kitaokeita/items/59b625e0c43a62f5fe6a このページの中に
class Relationship < ActiveRecord::Base belongs_to :follower, class_name: "User" belongs_to :following, class_name: "User" validates :follower_id, presence: true validates :following_id, presence: true end
のような記述があるのですが
belongs_to :follower, belongs_to :followingというところが理解できてません。
そのようなモデルはないのにどうやってこのような記述ができるのでしょうか?
class User < ActiveRecord::Base # 省略 has_many :following_relationships, foreign_key: "follower_id", class_name: "Relationship", dependent: :destroy has_many :followings, through: :following_relationships has_many :follower_relationships, foreign_key: "following_id", class_name: "Relationship", dependent: :destroy has_many :followers, through: :follower_relationships def following?(other_user) following_relationships.find_by(following_id: other_user.id) end def follow!(other_user) following_relationships.create!(following_id: other_user.id) end def unfollow!(other_user) following_relationships.find_by(following_id: other_user.id).destroy end end
この中のhas_many :relationshipとhas_many :followings_relationshipについても同様です。
よろしければ教えていただけるでしょうか?
あなたの回答
tips
プレビュー