0

前提・実現したいこと

投稿一覧ページにいいね機能をつけたい

発生している問題・エラーメッセージ

現在、投稿詳細ページ(show)にいいね機能を実装しております。
画像の説明をここに入力

投稿一覧ページ(index)に下記のソースコードを入力するとこのようなエラーが表示されます。
post_images/index.html.erb

<section class="sct-color-1 slice">
  <div class="container-fluid masonry-container">
    <div class="row">
      <div class="col-md-8 col-sm-offset-2">
        <div class="masonry-wrapper-cols">
          <div class="masonry-gutter"></div>
            <% @post_images.each do |post_image| %>
            <div class="masonry-block">
              <div class="block block-image v1">
                <div class="block-image">
                  <div class="view view-first">
                  <%= link_to post_image_path(post_image.id) do %>
                    <%= attachment_image_tag post_image, :image %>
                  <% end %>
                  </div>
                </div>
                <div class="block-content">
                  <%= attachment_image_tag post_image.user, :profile_image, size: "100x100", fallback: "no_image.jpg", class:"img-circle pull-left profile-thumb" %>
                  <h3 class="block-title">
                      <%= post_image.image_name %>
                  </h3>
                  <ul class="inline-meta">
                    <li>By
                      <%= post_image.user.name %>
                    </li>
                    <li>
                      <%= link_to "#{post_image.post_comments.count} コメント", post_image_path(post_image.id) %>


                    </li>
                    <% if @post_image.favorited_by?(current_user) %>
                      <li>
                        <%= link_to post_image_favorites_path(@post_image), method: :delete do %>
                          <i class="fa fa-star" aria-hidden="true" style="color: orange; font-size: 15px;"></i>
                          <%= @post_image.favorites.count %> ファイト
                        <% end %>
                      </li>
                    <% else %>
                      <li>
                        <%= link_to post_image_favorites_path(@post_image), method: :post do %>
                          <i class="fa fa-star" aria-hidden="true" style="font-size: 15px;"></i>
                          <%= @post_image.favorites.count %> ファイト
                        <% end %>
                      </li>


                    <% end %>
                  </ul>
                </div>
              </div>
            </div>
            <% end %>
            <%= paginate @post_images, class: "paginate" %>
        </div>
      </div>
    </div>
  </div>
</section>

エラー内容
画像の説明をここに入力

ソースコード

post_image.rb(model)

class PostImage < ApplicationRecord
    belongs_to :user
    attachment :image
    has_many :post_comments, dependent: :destroy
    has_many :favorites, dependent: :destroy
    validates :image_name, presence: true
    validates :image, presence: true
    def favorited_by?(user)
        favorites.where(user_id: user.id).exists?
    end
end

post_images_controller.rb(controller)

class PostImagesController < ApplicationController
    def new
        @post_image = PostImage.new
    end

    def create
        @post_image = PostImage.new(post_image_params)
        @post_image.user_id = current_user.id
        if @post_image.save
          redirect_to post_images_path
        else
          render :new
        end
    end

    def index
        @post_images = PostImage.page(params[:page]).reverse_order
    end

    def show
        @post_image = PostImage.find(params[:id])
        @post_comment = PostComment.new
    end

    def destroy
        @post_image = PostImage.find(params[:id])
        @post_image.destroy
        redirect_to post_images_path
    end

    private

    def post_image_params
        params.require(:post_image).permit(:image_name, :image, :caption)
    end
end

補足情報

定義されていないということは理解できるんですが、どう直せば表示されるのかがわかりません。
ご教示いただけると幸いです。

Rails 5.2.4.1
ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-linux-gnu]

追記

@post_imagesをpost_imageにしたら投稿一覧にいいねボタンが表示されるようになりました。

新たなエラーとして、いいねを押すと詳細ページに飛んでしまいます。
link_to post_image_favorites_path(@post_image)にしているためだと思われますが、indexのルートであるpost_images_pathと書いてもroutes errorが表示されてしまいます。

favorites_controller.rb(controller)

class FavoritesController < ApplicationController
    def create
        post_image = PostImage.find(params[:post_image_id])
        favorite = current_user.favorites.new(post_image_id: post_image.id)
        favorite.save
        redirect_to post_image_path(post_image)
    end

    def destroy
        post_image = PostImage.find(params[:post_image_id])
        favorite = current_user.favorites.find_by(post_image_id: post_image.id)
        favorite.destroy
        redirect_to post_image_path(post_image)
    end
end
5
  • 参考までに、過去にも類似質問があります。 - railsでいいね機能を付けたのですがうまくいいねが追加されません
    – cubick
    2020年1月6日 7:59
  • パッとみた感じ、@post_imageとなっているのはpost_imageの間違いではないかと思います。indexのviewへは、controllerからは@post_images(複数形のインスタンス変数)しか渡しておらず、view内で@post_images.eachで一つづつpost_image(単数形のローカル変数)に取り出し、それに対して処理を行っているように見えます。ちなみに、if文内の@post_imageも、全てpost_imageにしないとダメそうです。
    – sanadan
    2020年1月6日 8:21
  • @sanadan ご回答ありがとうございます。@を無くしたところ、投稿一覧に表示はされたのですが、いいねボタンを押すと詳細ページに飛んでしまいます。
    – user37337
    2020年1月6日 8:38
  • 1
    まずは、最初の質問は解決されたのですね。それでしたら、回答にどこをどのように直したら最初の問題が解決されたかを書き、承認済み(緑のチェックマーク)をつけましょう。そして、追記部分の質問を新たな質問として作り直してください。そうすることによって、質問と回答が複雑になるのを防ぎ、更にあなたの質問と回答が、同じような問題に行き着いた人の解決に役に立つようになるはずです。詳しくは右上の「?」アイコンをクリックして、ツアーなどを見てみてください。なお、新たな質問を作るときは、ソースは最初の問題が解決したものを引用するように気を付けてください。これによって、修正不足によるものか、元々問題があったのかがはっきりします。
    – sanadan
    2020年1月6日 14:12
  • @sanadan 承知しました。ご丁寧にありがとうございます。
    – user37337
    2020年1月6日 14:25

1 件の回答 1

1

@post_imagesをpost_imageに変更したら投稿一覧にいいね機能の表示をすることができました。

原因はindex.html.erbでは<% @post_images.each do |post_image| %>のように@post_imagespost_imageという変数に格納していたため。

2
  • エラーについて補足すると、今回の場合、indexが表示されるために@post_images(複数形のインスタンス変数/PostImageモデルのオブジェクトが複数格納される)はコントローラーのindexメソッド内で、post_image(単数形のローカル変数/@post_imagesから一つづつ取り出したもの)はビューの<% @post_images.each do |post_image| %>で作成されていますが、@post_image(単数形のインスタンス変数)は作成されていません。そのため、<% if @post_image.favorited_by?(current_user) %><% if nil.favorited_by?(current_user) %>と解釈され、しかしながらnilにはそのようなメソッドはないので、NoMethodErrorとなっています。Railsではよく単数形と複数形の使い分けが行われるので、今回のように@post_images@post_imagepost_imageが混ざって間違えるのを見かけます。今回は、他のメソッドでは@post_image(単数形のインスタンス変数/各メソッドでの処理対象になるPostImageオブジェクト)があり混乱しやすいので、注意が必要です。
    – sanadan
    2020年1月7日 6:22
  • 承知しました。ご丁寧にありがとうございます。
    – user37337
    2020年1月7日 7:51

この質問に回答するには、ログインする必要があります。