#質問内容
controllerからmodelのメソッドを参照する際、トピックcontroller7行目でトピックmodelのメソッドを呼び出せないのはなぜでしょうか?
#なぜこの質問をするのか(質問の背景)
adminというメソッドをmodelに定義してコントローラーから使いたいから。
controllerの条件式をメソッド化することで見る側の負荷を減らすために、簡単なコードにしたい。
#自分が思う仮説(私はこう思っている)
エラー文で未定義のメソッドと出てきたので、model側でのメソッドの定義の仕方に問題があるのではないかと思っているのですがどうでしょうか?
controller
1 def destroy 2 @topic = Topic.find_by(id: params[:id]) 3 @topic.destroy 4 flash[:notice] = "トピックを削除しました" 5 if admin 6 redirect_to(admin_path) 7 else 8 redirect_to("/") 9 end 10 end
model
1class Topic < ApplicationRecord 2 paginates_per 5 3 4 validates :title, {presence: true, length: {maximum: 40}} 5 validates :content, {presence: true, length: {maximum: 180}} 6 7 belongs_to :user 8 has_many :comments 9 10 def admin 11 @current_user.admin_status == true 12 end 13end
##追記:修正後の現状で躓いている点
ApplicationController↓
class ApplicationController < ActionController::Base before_action :set_current_user def set_current_user @current_user = User.find_by(id: session[:user_id]) end end
topicコントローラー↓
def destroy @topic = Topic.find_by(id: params[:id]) @topic.destroy flash[:notice] = "トピックを削除しました" if @current_user.admin redirect_to(admin_path) else redirect_to("/") end end
userモデル↓
class User < ApplicationRecord has_secure_password validates :name, {presence: true} validates :email, {presence: true, uniqueness: true} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+.[a-z]+\z/i validates :email, presence: true, uniqueness: true, format: { with: VALID_EMAIL_REGEX ,message: "形式が間違っています" } has_many :topics has_many :comments def admin @current_user.admin_status == true end end
としています。
呼び出し方としてUserクラスにadminという
インスタンスメソッドを定義しています。
ApplicationControllerのbefore_actionで定義されている、@current_userを使い定義し実行しました。しかし今度は
@current_user.admin_status == true
でNoMethodErrorが発生してしまいます。。。
何がいけないのでしょうか?;;
回答3件
あなたの回答
tips
プレビュー