rails posts/indexページに各投稿のいいね数を表示させたいのですが数字が全く表示されません 初心者のため凡ミスかもしれません
Q&A
Closed
解決したいこと
railsでindexページにいいね数を表示させたい
発生している問題・エラー
NameError in Posts#index
Showing /Users/app/views/posts/index.html.erb where line #42 raised:
undefined local variable or method `likes_count' for #<ActionView::Base:0x000000000260c0>
'.freeze;@output_buffer.append=( likes_count );@output_buffer.safe_append='
<%= likes_count %>
該当するソースコード
posts/index.html.erb
<% if @current_user && Like.find_by(user_id: @current_user.id, post_id: post.id) %>
<%= link_to("/likes/#{post.id}/destroy", {method: "post"}) do %>
<span class="fa fa-heart liked-btn"></span>
<% end %>
<% else %>
<%= link_to("/likes/#{post.id}/create", {method: "post"}) do %>
<span class="fa fa-heart unliked-btn"></span>
<% end %>
<% end %>
<%= likes_count %>
 
<%= post.created_at.strftime('%Y/%m/%d %H:%M') %>
posts/show.html.erb
<div class="post-time">
<%= @post.created_at.strftime('%Y/%m/%d %H:%M') %>
</div>
<% if @current_user && Like.find_by(user_id: @current_user.id, post_id: @post.id) %>
<%= link_to("/likes/#{@post.id}/destroy", {method: "post"}) do %>
<span class="fa fa-heart liked-btn"></span>
<% end %>
<% else %>
<%= link_to("/likes/#{@post.id}/create", {method: "post"}) do %>
<span class="fa fa-heart unliked-btn"></span>
<% end %>
<% end %>
<%= @likes_count %>
showページは問題なく表示されています
posts_controller.rb
def index
@posts = Post.all.order(created_at: :desc)
end
def show
@post = Post.find_by(id: params[:id])
@user = @post.user
@likes = Like.where(user_id: @user.id)
@likes_count = Like.where(post_id: @post.id).count
@comments_count = Comment.where(post_id: @post.id).count
@comment = Comment.new
@comments = @post.comments.includes(:user)
@post_detail = Post.find(params[:id])
if @current_user.present?
unless ViewCount.find_by(user_id: @current_user.id, post_id: @post_detail.id)
@current_user.view_counts.create(post_id: @post_detail.id)
end
end
end
最後まで読んでいただきありがとうございます。
ご教授いただけると幸いです。
0 likes