ユーザーフォロー6
やった事
- フォローする時のcreateアクションの実装
- フォロー解除する時のdestroyアクションの実装
- railsガイドを読んだ
参考資料
Active Record の関連付け - Railsガイド
createアクション
ネタバレになりそうなので折りたたみます
コントローラー
app/controllers/follow_relationships_controller.rb
①books_controller.rbを参考に書いてみたもの。きちんと動いた。
def create
@follow_relationship = current_user.active_relationships.build(followed_id: params[: followed_id])
@follow_relationship.save!
redirect_to user_path(params[:followed_id])
end
②createメソッドを使ったもの
def create
@follow_relationship = current_user.active_relationships.create(followed_id: params[:followed_id])
redirect_to user_path(params[:followed_id])
end
③Railsチュートリアルのやり方<<
を使い配列に入れるようにDB登録できる!
def create
user = User.find(params[:followed_id])
current_user.following << user
redirect_to user_path(user)
end
Railsガイドを見ると色々なメソッドがあるので、色々なやり方があるのかなと思い、書いて実行してみた。
ログを見るとどれも同じSQL内容の様。
どれも違いがないのであれば、分かりやすい書き方が一番良いのか?
モデル
モデルに関しての処理はモデルにメソッドを作り、コントローラーから渡す様。
②のモデルに関する処理をapp/models/user.rb
に移してみた
def follow(other_user_id)
active_relationships.create(followed_id: other_user_id)
end
③railstチュートリアルのやり方
どう考えてもこれが分かりやすい!!
def follow(other_user)
following << other_user
end
destroyアクション
ネタバレになりそうなので折りたたみます
修正前
def destroy
@follow_relationship = current_user.active_relationships.find(params[:id])
@follow_relationship.destroy
redirect_to user_path(@follow_relationship.followed_id)
end
params[:id]
で持ってくるidはactive_relationshipsテーブルのmodel:current_user.active_relationships.find_by(followed_id: @user.id)
のレコードのidになる!ここが分かりづらい!
⇩(form_withで渡しているもの)
<%= form_with(model: current_user.active_relationships.find_by(followed_id: @user.id ),html: { method: :delete }, local: true) do |f| %>
修正後
モデルにアンフォローに関するコードを移すのに分かりずらく、結局railsチュートリアルを参考にコードを書き換えた。app/controllers/follow_relationships_controller.rb
def destroy
user = FollowRelationship.find(params[:id]).followed
current_user.unfollow(user)
redirect_to user_path(user)
end
app/models/user.rb
def unfollow(other_user)
active_relationships.find_by(followed_id: other_user.id).destroy
end