現在、いいね機能を非同期通信で実装しているのですが下記エラーが発生してしまいます。
非同期にする前は問題なく動作していました。
どなたか回答お願いします。。
ActionView::Template::Error (undefined method `favorited_by?' for nil:NilClass): 1: - if @recruitment.favorited_by?(current_user) 2: /ログインしているユーザーがファボしたかどうかで分岐 3: .recruitment__box__btn 4: .recruitment__box__btn__box app/views/favorites/_favorite.html.haml:1:in `_app_views_favorites__favorite_html_haml__1751749382388006018_70287961722780' app/views/favorites/destroy.js.erb:1:in `_app_views_favorites_destroy_js_erb__4278231835027885942_70287985797460'
該当箇所のコード
favorites/favorite.html.haml - if @recruitment.favorited_by?(current_user) /ログインしているユーザーがファボしたかどうかで分岐 .recruitment__box__btn .recruitment__box__btn__box = link_to 'いいね解除', recruitment_favorites_path(@recruitment.id), method: :delete, remote: true, class:"recruitment__box__btn__box__link" %p.recruitment__box__btn__box__favorite %i.fas.fa-heart = @recruitment.favorites.count - else .recruitment__box__btn .recruitment__box__btn__box = link_to 'いいね', recruitment_favorites_path(@recruitment.id), method: :post, remote: true, class:"recruitment__box__btn__box__link" %p.recruitment__box__btn__box__favorite %i.fas.fa-heart = @recruitment.favorites.count
recruitment_model class Recruitment < ApplicationRecord belongs_to :user has_many :favorites def favorited_by?(user) favorites.where(user_id: user.id).exists? end def self.search(search) if search Recruitment.where('recruitment_type LIKE(?)', "%#{search}%") else Recruitment.all end end end
favorites_controller class FavoritesController < ApplicationController def create favorite = current_user.favorites.build(recruitment_id: params[:recruitment_id]) favorite.save end def destroy favorite = Favorite.find_by(recruitment_id: params[:recruitment_id], user_id: current_user.id) favorite.destroy end end
create.js.erb $('#favorites_buttons').html("<%= j(render 'favorites/favorite') %>");
destroy.js.erb $('#favorites_buttons').html("<%= j(render 'favorites/favorite') %>");
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。