Ruby(Rails)初学者で初めてのオリジナルアプリを作成しているのですがNoMethodError in PostsController#showというエラーが出てしまい解消できずにいます
このエラーについて調べてみたところ、同じようなエラーでデータベースのデータを消去したら解消されたという方やbelongs_to :user やhas_many :users をmodelに入れたら解決したという方がいらっしゃったのでしたが、データベースのデータを消去しても解消できませんでしたし、下記のコードにある通りbelongs_to :user やhas_many :users はあるのでなにが原因で起きているエラーなのかすらわからずにいます
発生している問題・エラーメッセージ
NoMethodError in PostsController#show undefined method `user_id' for nil:NilClass Extracted source (around line #14): @post = Post.find_by(id: params[:id]) @user = User.find_by(id: @post.user_id) end
#14というのは @user = User.find_by(id: @post.user_id)の部分です
該当のソースコード
**controllers - posts_controller.rb** class PostsController < ApplicationController before_action :authenticate_user before_action :ensure_correct_user,{only:[:edit,:update,:destroy]} def index @posts = Post.all.order(created_at: :desc) end def show @post = Post.find_by(id: params[:id]) # 変数@userを定義してください @user = User.find_by(id: @post.user_id) end def new @post = Post.new end def create @post = Post.new( content:params[:content], user_id: @current_user.id ) if @post.save redirect_to("/posts/index") else render("posts/new") end end def edit @post = Post.find_by(id: params[:id]) end def update @post = Post.find_by(id: params[:id]) @post.content = params[:content] if @post.save redirect_to("/posts/index") else render("posts/edit") end end def destroy @post = Post.find_by(id: params[:id]) @post.destroy redirect_to("/posts/index") end def ensure_correct_user @post = Post.find_by(id: params[:id]) if @post.user_id != @current_user.id flash[:notice]= "権限がありません" redirect_to("/posts/index") end end end
**model - user.rb** class User < ApplicationRecord has_secure_password validates :name, {presence: true} validates :email, {presence: true, uniqueness: true} has_many :posts def posts return Post.where(user_id: self.id) end end
**model - post.rb** class Post < ApplicationRecord validates :content, {presence: true ,length:{maximum:140}} validates :user_id,{presence:true} belongs_to :user end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/19 13:56