Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

rails 各アイテムにコメント数やいいね数、閲覧数を表示させたいのですがやり方がわかりません 初心者のため説明が下手かもしれませんがよろしくお願いします。

解決したいこと

スクリーンショット 2023-02-27 17.22.42.png
この投稿された日時の下か横に
スクリーンショット 2023-02-27 17.23.48.png
この3つの数をそれぞれの投稿の内容の数に合致したものを表示させたいです

posts/index.html.erb
        <div class="post-right">
          <div class="post-user-name">
            <%= link_to(post.user.name, "/users/#{post.user.id}") %>
          </div>
          <div class="post-title">
            <%= link_to(post.title.truncate(30), "/posts/#{post.id}") %>
          </div>

          <%= post.created_at.strftime('%Y/%m/%d %H:%M') %>
          
        </div>
posts/show.html.erb
        <%= link_to("/likes/#{@post.id}/create", {method: "post"}) do %>
          <span class="fa fa-heart unliked-btn"></span>
        <% end %>
      <% end %>
      <%= @likes_count %>

        &emsp;

      <span class="fa fa-eye"></span>
      <%= @post_detail.view_counts.count %>

        &emsp;

      <span class="fa fa-comment"></span>
      <%= @comments_count %>

最後まで読んでいただきありがとうございます
ご教授いただけると幸いです

半年間この問題が解決出来ず困っています

0 likes

1Answer

まず、各アイテム(postの事でしょうか)に対して、「いいね数」や「コメント数」をどのように持たせているのでしょうか?それが不明なのでアドバイスができない状況です。

例1) 直接 posts テーブルに紐づける場合

  • posts.count_good
  • posts.count_comment

など、カラムとして持たすような設計にすれば、表示する方法は言わずもがなですよね。

例2)別テーブルで紐づける場合
いいね ---> good_items テーブル
コメント ---> comment_items テーブル

とそれぞれの履歴を別テーブルで管理する場合、 Post モデルファイルにて

class Post< ApplicationRecord
  has_many :good_items
  has_many :comment_items

のように、親子関係を作ります。そして表示( views)では以下のように

いいね数:<%= @post.good_items.count %>
コメント数:<%= @post.comment_items.count %>

で表現できるはずです。

0Like

Your answer might help someone💌