いいねボタンを作成するためのcreateアクションを作成
初めに
- Progateを学習中に躓いたところを中心にアウトプットするのと同時に備忘録がてらに記事を書いていきます!
現状
likes_controller内にcreateアクションを定義したが中身は空のまま。
createアクションに関するルーティングは
post "likes/:post_id/create" => "likes#create"
自分が書いたコード
likes_controller
class LikesController < ApplicationController before_action :authenticate_user def create @like = Like.new(user_id :@current_user.id, post_id :@post.id @like.save redirect_to("/posts/#{params[:post_id]}") end
- authenticate_userはapplicarion_controllerで
def authenticate_user if @current_user == nil flash[:notice] = "ログインが必要です" redirect_to("/login") end end
としている。
- @postが定義されていないのでエラーの対象となる。
実際のコード
likes_controller
def create @like = Like.new(user_id :@current_user.id, post_id :params[:post_id]) @like.save redirect_to("/posts/#{params[:post_id]}") end
いいね!を作るためにはユーザーのidと投稿のidの2つが必要。
例えばLike.new(user_id: 1, post_id: 2)となるとuser1がpost1にいいねしたというコードになる。
post_id :@post.id→post_id :params[:post_id]に変更した。
createのルーティングよりpost "likes/:post_id/create" => "likes#create"からpost_idは送られていて、 Like.newに入れれば良いのでpost_id :params[:post_id]となる
結語
post_idの値はルーティンで記載されてあるURLのpost_idに含まれている。
paramsはURLの値を捕まえる役割がある。