ユーザーがいいねを押した投稿をマイページに表示させるようにしたいのですが
エラーになるため教えていただきたいです。
likes = like.where(user_id: current_user.id).pluck(:preschool_id)
こちらに
undefined local variable or method `like' for #<UsersController:0x00007f960e335008> Did you mean? likes
というエラーが出たのですがlike→likesに変更をすると
undefined method `where' for nil:NilClass Did you mean? when
というエラーになります。
###該当コード
rails
1class UsersController < ApplicationController 2 def show 3 @user = User.find(params[:id]) 4 likes = like.where(user_id: current_user.id).pluck(:preschool_id) 5 @like_list = preschool.find(likes) 6 end 7end
show.html.erb
1<div class='preschool-contents'> 2 <ul class='preschool-lists'> 3 <li class='list'> 4 <% @preschools.each do |preschool| %> 5 <%= link_to preschool_path(preschool.id) do %> 6 <div class='preschool-img-content'> 7 <% preschool.images.each do |image|%> 8 <%= image_tag(preschool.images[0], class:"preschool-img")%> 9 </div> 10 <div class='preschool-info'> 11 <h3 class='preschool-name'><%= preschool.name %></h3> 12 <h3 class='preschool-concept'><%= preschool.concept %></h3> 13 </div> 14 <% end %> 15 <% end %> 16 17 <% if user_signed_in? && current_user.already_liked?(preschool) %> 18 <%= link_to "いいね解除",preschool_likes_path(preschool), method: :delete %> 19 <%= preschool.likes.count %> 20 <% elsif user_signed_in? %> 21 <%= link_to "いいね!", preschool_likes_path(preschool), method: :post %> 22 <%= preschool.likes.count %> 23 <% end %> 24 <% end %>
ルーティング↓
Rails.application.routes.draw do //省略 resources :users, only: [:show] do get :likes, only:[:create,:destroy] end resources :preschools do resources :comments, only:[:create,:edit,:update,:destroy] resource :likes, only:[:create,:destroy] end end
likesコントローラー↓
class LikesController < ApplicationController def create @like = current_user.likes.create(preschool_id: params[:preschool_id]) redirect_back(fallback_location: root_path) end def destroy @preschool =Preschool.find(params[:preschool_id]) @like = current_user.likes.find_by(preschool_id: @preschool.id) @like.destroy redirect_back(fallback_location: root_path) end end
userモデル↓
class User < ApplicationRecord //省略 def already_liked?(preschool) self.likes.exists?(preschool_id: preschool.id) end has_many :likes //省略 end
###バージョン
rails 6.0.0
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/12/28 08:22