Search code examples
ruby-on-railsrubystrong-parameters

Getting Started With Rails Tutorial: 5.7 Showing posts -- No Forbidden Attributes Error


I've been following this Rails tutorial:

http://guides.rubyonrails.org/getting_started.html

Section 5.7 tells me that I should expect an ActiveModel::ForbiddenAttributesError

The thing is, I don't get the error. It works without the permit keyword.

My create method looks like this:

  def create
    @post = Post.new(post_params)
    @post.save
    redirect_to @post
  end

I'm working with Rails 4.0 and Ruby 2.0. Any idea why the strong parameters security function isn't working?


Solution

  • The documentation is actually misleading, you're right.

    If you coded your controller as shown in chapter 5.6

    def create
      @post = Post.new(post_params)
    
      @post.save
      redirect_to @post
    end
    
    private
      def post_params
        params.require(:post).permit(:title, :text)
     end
    

    you're already permitting the use of the parameters title and text.

    The next chapter (5.7) assumes you didn't use the permit-method already.

    If you'd change Line 2 to:

     @post = Post.new(post_params)
    

    as seen in the screenshot, the error will be thrown. Additionally, the 'fix' in chapter 5.7 doesn't define a new private method post_params as you did, but applies the fix inline.

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