user3440243
user3440243

Reputation: 13

undefined method `permit' for nil:NilClass in Rails Guide Section 5.12

I am stuck at section 5.12 and I could not figure it out that how params[:post] is nil. The error message specifies the error occurs in the third line of this code:

      def edit
        @post = Post.find(params[:id])
        if @post.update(params[:post].permit(:title, :text))
          redirect_to @post
        else
          render 'edit'
        end
      end

My posts_controller file looks like this:

    class PostsController < ApplicationController
      def new
        @post = Post.new
      end

      def index
        @posts = Post.all
      end

      def create
        @post = Post.new(params.require(: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])
        if @post.update(params[:post].permit(:title, :text))
          redirect_to @post
        else
          render 'edit'
        end
      end
    end

Upvotes: 1

Views: 591

Answers (2)

Kirti Thorat
Kirti Thorat

Reputation: 53038

First of all, edit action is used to render the edit post page. So, you won't get params[:post]. It will always be nil. Hence, the error.

So your edit action should be:

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

After this you need to add the following update action in your controller which would be called upon submitting the form on edit post page.

 def update
    @post = Post.find(params[:id])
    if @post.update(params.require(:post).permit(:title, :text))
      redirect_to @post
    else
      render 'edit'
    end
  end

This will take care of current issue.

NOTE:

I would highly recommend to move the repetitive logic for params.require(:post).permit(:title, :text) into a private method as suggested by @user3317140 in his answer.

Upvotes: 1

HackerKarma
HackerKarma

Reputation: 620

EDIT: add a check for :post

if params.has_key?(:post)
  @post.update(params[:post].permit(:title, :text))
  redirect_to @post
else
  render 'edit'
end

Add this at the end of your class PostsController < ApplicationController

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

Upvotes: 0

Related Questions