###実現したいこと
view/posts/index.html.slimでcurrent_user.admin?を使えないのはなぜでしょうか。
発生している問題・エラーメッセージ
メソッドが見つかりませんと出ます
エラーメッセージ ActionView::Template::Error (undefined method `admin?' for nil:NilClass):
該当のソースコード
ruby
1@該当箇所 2- if current_user.admin? 3 = link_to '編集', edit_post_path(plan), class: 'btn btn-primary mr-3' 4 = link_to '削除', post,method: :delete, data:{confirm: "「#{post.title}」を削除します。よろしいですか?"}, class: 'btn btn-danger' 5 6@current_user指定場所(controllers/application_controller.erb) 7class ApplicationController < ActionController::Base 8 helper_method :current_user 9 10 11 private 12 13 def current_user 14 @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id] 15 end 16end 17 18@posts_controllerのindexアクション 19 def index 20 @q = Plan.ransack(params[:q]) 21 @plans = @q.result(distinct: true).page(params[:page]).per(15).recent 22 end
試したこと
indexアクションに@user = User.find_by(params[:id])を追加して、
if current_user.admin?の部分を @user.admin?にしたらエラーが起きなくなった。
しかし、なぜcurrent_userだとadmin?メソッドが効かないのか。
また、view/users/index.html.slimではif current_user.admin?でエラーなく実装することができました。
それはなぜなのでしょうか。どなたかご教授いただけると幸いです。
補足情報(FW/ツールのバージョンなど)
Ruby version 2.6.3
Rails 5.2.3
回答2件
あなたの回答
tips
プレビュー