このサイトをもとにいいね機能を作っているのですが記事通りに進めてもNoMethodError (undefined method `id' for nil:NilClass) が出てしまいます。
idの中身が無いようですがどのように改善すれば成功するのでしょうか。
詳しい方教えて下さいましたら幸いです。
index.html.erb
index.html.erb
1<div class="tweet-card"> 2 <% @posts.each do |post| %> 3 <div class="card"> 4 <div class="stream-item"> 5 <div class="content"> 6 <div class="stream-item-header"> 7 <%= image_tag current_user.profile_photo, class: "avatar avatar-size48" %> 8 <div class="user-profile-link"> 9 <%= link_to "@" + "#{post.user.username}", "#", class: "username" %> 10 </div> 11 <div class="time"> 12 ・<%= time_ago_in_words(post.created_at) %> 13 </div> 14 </div> 15 <div class="tweet-text"> 16 <%= safe_join(post.text.split("\n"), tag(:br)) %> 17 </div> 18 <% if Like.find_by(user_id: @current_user.id, post_id: @post.id) %> 19 <%= link_to("/likes/#{@post.id}/destroy", {method: "post"}) do %> 20 <span class="fa fa-heart like-btn-unlike"></span> 21 <% end %> 22 <% else %> 23 <%= link_to("/likes/#{@post.id}/create", {method: "post"}) do %> 24 <span class="fa fa-heart like-btn"></span> 25 <% end %> 26 <% end %> 27 </div> 28 </div> 29 </div> 30 <% end %> 31</div>
like_controller.rb
class LikesController < ApplicationController def create @like = Like.new(user_id: @current_user.id, post_id: params[:post_id]) @like.save redirect_to("/posts/#{params[:post_id]}") end def destroy @like = Like.find_by(user_id: @current_user.id, post_id: params[:post_id]) @like.destroy redirect_to("/posts/#{params[:post_id]}") end end
###like.erb
class Like < ApplicationRecord validates :user_id, {presence: true} validates :post_id, {presence: true} end