Railsチュートリアル 第14章 メモ書き
プログラミングの学習をとりあえず挙げていくと言ったくせに、
すぐに三日坊主になってしまった人です。
プログラミングの学習自体は続けてました。
チュートリアルのメモ書きは13章まで上げていましたが、14章もメモに書くだけ書いて放置していたので、上げておきます。
○フォローとアンフォロー
・フォロー中→following
フォロワー達→followed
・relationshipカラムでフォローとフォロワーの関係を構築
→follower_idとfollowed_id
・複合キーインデックス
→ add_index :relationships, [:follower_id, :followed_id], unique: true
follower_idとfollowed_idの組み合わせが必ずユニークであることを保証
・外部キー:
2つのデータベーステーブルを繋ぐid
場合によっては以下のようにクラス名を明示しなければならない。
has_many :active_relationships, class_name: "Relationship"
belongs_to :followed, class_name: "User"
・has_many_through:
has_many :followeds, through: :active_relationships
だとrelationshipテーブルのfollowed_idを使って対象のユーザーを取得。
但し、followedsでは文法的に正しくないため、:sourceパラメーターを使って、
「following配列の元はfollowed idの集合である」ことrailsに示す。
has_many :following, through: :active_relationships, source: :followed
・# ユーザーをフォローする
def follow(other_user)
f ollowing << 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
・複数のルーティング設定:
resources :users do
member do
get :following, :followers
end
end
→users/1/following やusers/1/followed
Idの指定をしない場合、memberではなくcollection
・AjaxによるHTML の表示
form_with(model: ..., remote: true)
local→remoteに
・ステータスフィード
1)フォローしているユーザーのマイクロポストがフィードに含まれていること。
2)自分自身のマイクロポストもフィードに含まれていること。
3)フォローしていないユーザーのマイクロポストがフィードに含まれていないこ
と。
・Railsは低級なクエリを呼び出せる
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end