Search code examples
ruby-on-railsrubynomethoderror

Encountered error "NoMethodError in Posts#show"


I am new in ruby on rails in windows.. I am following some guide through youtube, but I encountered error

Question: In part of <%= @post.item %>, what should I put in @post?. Is it my method or the name of the field in my another view?

"NoMethodError in Posts#show undefined method `item' for nil:NilClass Extracted source (around line #2): 1 2 <%= @post.item %> # the error indicates here 3 4 5 Submitted:<%= time_ago_in_words(@post.created_at) %> Ago 6

Controller

class PostsController < ApplicationController
    def index
    end
    def addItem
    end
    def create
      @post = Post.new(post_params)
      @post.save
      redirect_to @post
    end
    private
        def post_params
            params.require(:post).permit(:item, :description)
        end
    def show
        @post = Post.find(params[:id])
    end
end

Show.html.erb view

<h1 class="item">
    <%= @post.item %>
</h1>
<h1 class="date">
    Submitted:<%= time_ago_in_words(@post.created_at) %> Ago
</h1>
<h1 class="description">
    <%= @post.description %>
</h1>
<h1 class="date">
    Submitted:<%= time_ago_in_words(@post.created_at) %> Ago
</h1>

Routes

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :posts
  root "posts#index"
  resources :posts
  root "posts#addItem"
end

Solution

  • In Ruby, All the methods you add below private keyword becomes private methods.

    In your case, show method is a private one, hence @post variable is not available in view.

    Change your posts_controller code to this

    class PostsController < ApplicationController
    
        def index
        end
    
        def create
          @post = Post.new(post_params)
          @post.save
          redirect_to @post
        end
    
        def show
          @post = Post.find(params[:id])
        end
    
        def addItem
        end
    
        private
          def post_params
            params.require(:post).permit(:item, :description)
          end
    end