Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

rails posts/indexページに各投稿のいいね数を表示させたいのですが数字が全く表示されません 初心者のため凡ミスかもしれません

解決したいこと

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 %>

          &emsp;

          <%= 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

1Answer

(1)post_id: 件数のMap構造を作る

posts_controller.rb
def index
  @posts = Post.all.order(created_at: :desc)
+ @post_like_count = Like.group(:post_id).count
end

(2)(1)で作ったMap構造から件数を取り出す

posts/index.html.erb
- <%= likes_count %>
+ <%= @post_like_count[post.id] %>
0Like

Comments

  1. @NetaNeta0620

    Questioner

    表示できました!
    ありがとうございます。

    それと、コメントの数と閲覧数も同様にindexに表示させるためにはこれと同様な形でコードを組めばいいでしょうか?

Your answer might help someone💌