Friday, November 22, 2013

How to solve “undefined method `title' for nil:NilClass” in Rails Tutorial

If you are following http://guides.rubyonrails.org/getting_started.html or similar, you may get the awful  “undefined method `title' for nil:NilClass” problem. In that case, just go over to app\controllers\post_controllers.rb and put all "private" headers at the bottom. For example, if you have,

private
      def post_params
        params.require(:post).permit(:title, :text)
      end

which you should, as it's part of the tutorial, then make sure this block, and any others that say anything about being private, as far down the column as possible. Here's how mine ended up looking afterward:

class PostsController < ApplicationController

    def new
    end

    def create
      @post = Post.new(post_params)

      @post.save
      redirect_to @post
    end

    def show
      @post = Post.find(params[:id])
    end

    private
      def post_params
        params.require(:post).permit(:title, :text)
      end

    end

--
Condensed from: http://stackoverflow.com/questions/17810348/undefined-method-title-for-nilnilclass-rails-guides-tutoraial

5 comments: