2020/12/21 railsチュートリアル14章後半
rails console実行しても生成したRelationshipモデルを認識してくれなくなり中断
出たエラー
irb(main):002:0> Relationship.new Traceback (most recent call last): 1: from (irb):2 NameError (uninitialized constant Relationship)
console再起動したり、destroy modelしてやり直したり、gitで作成前のバージョンに戻ってやり直したりしても解消しなかったので、RUNTEQの方に初質問(緊張)
結果、
spring stop
のコマンドを実行しただけで解決。
springはrails consoleでのコマンドの実行を早くしてくれる機能らしい。他に影響を及ぼすことはないので、エラーかと思ったら実行して支障ないとのこと。
has_many through
#userモデルに追記 has_many :following, through: :active_relationships, source: :followed
やりたいこと
user(follower)がフォローしているユーザーの集合(followed)が欲しい!
irb(main):001:0> user = User.first => #<User id: 1, reset_digest: nil, reset_sent_at: nil ...> irb(main):002:0> user.active_relationships.map(&:followed) => userをfollowしている一覧が出せる #userのactive_relationshipsの集合をだし、その集合に対しfollwedというメッセージを投げて帰ってきた一覧をまとめて出してください
has_many :following => というメソッドを作る
through: :active_relationships => active_ralationshipsメソッドを実行し、
source: :followed => その結果にfollowedメソッドを実行した結果
=> user.active_relationships.map(&:followed)と同じ!
# ユーザーをフォローする def follow(other_user) following << other_user end
following << other_user => other_userをfollowingの配列に追加する
# ユーザーをフォロー解除する def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end
引数に渡されたIDがfollowed_idに含まれるrelationshipのデータを削除する
# 現在のユーザーがフォローしてたらtrueを返す def following?(other_user) following.include?(other_user) end
引数に渡されたユーザーがfollowingの集合に含まれているか?trueかfalse
フォロワーを考える
has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :followers, through: :passive_relationships, source: :follower #passive_relationshipsで返ってきた集合に、followメソッドを呼び出した結果