"undefined method `title' for nil:NilClass" Rails Guides Tutorial
you have made your methods private. Remember where you put private keyword. all the methods below that, will become private, define your methods like this. private methods in end of the controller :
class PostsController < ApplicationController
def new
@post = Post.new
end
def index
@posts = Post.all
end
def create
@post = Post.new(params[:post].permit(:title, :text))
if @post.save
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :text))
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
Hope it will help. Thanks
I met the same problem as you when following the tutorial. And I checked my codes again then found the reason. In the posts_controller.rb file, you cannot put the private method in the middle of the codes, that means all the methods below (such as show, edit) will be private. Instead, put the private method at the bottom like this:
class PostsController < ApplicationController
def new
end
def index
@posts = Post.all
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
Hope to solve your problem.