RailsTutorial14章
index
add_index :relationships, :follower_id add_index :relationships, :followed_id add_index :relationships, [:follower_id, :followed_id], unique: true
高速化のため。
add_index :relationships, [:follower_id, :followed_id], unique: true
2つを揃って検索することが考えられるためこのような記法になる。
モデルについて
app/models/user.rb
class User < ApplicationRecord has_many :microposts, dependent: :destroy has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy . . . end
microposts
デフォルトだと class_name: "Micropost"
foreign_key: "user_id" 自明だったので書かなかった。
=> "#{Model Name}s"が規約
規約に則っていないから追加している。 active_relationships このままだとactive_relashionship model (class)を探しに行っちゃうのでRelationshipを指定する このままだとUsetrモデルを探しにいく?のでfollow_idだと分からせる。 has_manyはたくさんのメソッドを生成する。そのときに使用するのはRelationshipを使ってね
UserのidとRelationshipテーブルのfollower_id が紐付いている
app/models/relationship.rb
class Relationship < ApplicationRecord belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User" end
class_nameをつけないと"#{Model Name}s"が規約 Follwer_id, Follwerクラスを探しに行ってしまうから
Relationshipテーブルのfollower_idとUserのidが紐付いている Relationshipテーブルのfollowed_idとUserのidが紐付いている
belongs_to
, has_many
はメソッドを生成するメソッド
has_many throughについて
Userに紐付いたrelationshipのidが欲しいわけではなく user.followingが欲しいという動機
@user.active_relationships.map(&:followed) 上でも呼び出せるけどめんどくさいからメソッドを作ろうよという流れ
has_many :following, through: :active_relationships, source: :followed
followingメソッド
Userクラスのインスタンスに対して active_relationshipsメソッドを実行し、それで得られたそれぞれのRelationshipテーブル のインスタンスに対してfollowedメソッドを実行したものを返してくれるもの
便利クラス
def follow(other_user) following << other_user end # ユーザーをフォロー解除する def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end # 現在のユーザーがフォローしてたらtrueを返す def following?(other_user) following.include?(other_user) end
共通のパーシャル
JavascriptによるAjaxの実装