Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoMethodError in PostsController#create

Forgive my ignorance but I am brand new not only to Ruby but programming in general. I am working through the example on edge guides at rubyonrails.org. and am receiving the following error and despite reviewing every piece of code I've typed since the app last worked I am unable to fix it.

NoMethodError in PostsController#create

undefined method `permit' for {"title"=>"", "text"=>""}:ActiveSupport::HashWithIndifferentAccess

And this is what my posts_controller.rb looks like:

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

  def create
    @post = Post.new(params[:post].permit(:title, :text))

    if @post.save
      redirect_to action: :show, id: @post.id
    else
      render 'new'
    end    
  end

  def show
    @post = Post.find{params[:id]}
  end  

  def index
    @posts = Post.all
  end        
end

What am I doing wrong?

Thank you in advance for any help!

like image 787
user2299914 Avatar asked Apr 19 '13 16:04

user2299914


2 Answers

Instead of this line:

@post = Post.new(params[:post].permit(:title, :text))

Try this

 @post = Post.new(params[:post])

It looks like you ran across strong_parameters and had a few tutorial mixups.

If you do want to use strong_parameters, add the gem to your Gemfile and create an initializer with the following:

ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

Then your controller can be:

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

  def create
    @post = Post.new(post_params)

    if @post.save
      redirect_to action: :show, id: @post.id
    else
      render 'new'
    end    
  end

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

  def index
    @posts = Post.all
  end    

  private

  def post_params
    params.require(:post).permit(:title, :text)
  end    
end
like image 138
silasjmatson Avatar answered Sep 21 '22 22:09

silasjmatson


Which version of Rails are you using? #permit is a new feature to be added in Rails 4.0 to prevent mass assignment. So if you're on 3.2, you will need to add the strong_parameters gem to support this functionality. Alternatively, you can drop the .permit(:title, :text) in the PostsController#create and add the following to your Post model:

attr_accessible :title, :text

This is done in order to prevent a attacker from tampering with the submitted form data and updating some unauthorized field (e.g. 'is_admin', or something of the sort.

More details here.

like image 33
Ruy Diaz Avatar answered Sep 17 '22 22:09

Ruy Diaz