steven_noble
steven_noble

Reputation: 4203

Why am I getting an ActiveModel::ForbiddenAttributesError

I while ago I migrated to Rails 4 but initially I used the "protected_attributes" gem.

Now, I've removed that gem, and I think I'm using strong parameters correctly, but I'm getting the following error. Why?

From: /Users/steven/Dropbox/Testivate/app/controllers/categories_controller.rb @ line 21 CategoriesController#create:

    20: def create
 => 21:   binding.pry_remote
    22:   @category = Category.new(params[:category]).permit(:name)
    23:   flash[:notice] = "Category was successfully created." if @category.save
    24:   respond_with(@category)
    25: end

[1] pry(#<CategoriesController>)> params
=> {"utf8"=>"✓",
 "category"=>{"name"=>"Clothes"},
 "commit"=>"Create Category",
 "action"=>"create",
 "controller"=>"categories"}
[2] pry(#<CategoriesController>)> @category = Category.new(params[:category]).permit(:name)
ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError
from /Users/steven/.rvm/gems/ruby-2.1.0/gems/activemodel-4.0.2/lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'
[3] pry(#<CategoriesController>)> 

I have commented out the config.active_record.mass_assignment_sanitizer statement in development.rb and I have no config.active_record.whitelist_attributes statement in my application.rb.

Upvotes: 0

Views: 1969

Answers (2)

Paritosh Praharaj
Paritosh Praharaj

Reputation: 33

This is a good use case of using Rails Strong Parameters. Imagine, you have a Cuisine Model, and it has a Name, A Brief Description and an Associated Pic. So, your Cuisine Controller will have its Strong Parameter used this way.

class CuisineController < ApplicationController
    #method for strong parameters
    def required-fields-for-cuisine-form
        params.require(:cuisine).permit(:name, :brief-description, :associated-pic)    
    end

    #method for Form for Creating a Cuisine Record
    def create_cuisine
        @cuisine = Cuisine.new(required-fields-for-cuisine-form)
        if @cuisine.save
            flash[:success] = "Your cuisine has been saved."
            redirect_to cuisine_path(@cuisine)
        end
    end

This Github *READ ME* from the Rails Team shows how you could use Strong Parameters: https://github.com/rails/strong_parameters

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

This should work:

@category = Category.new(params.require(:category).permit(:name))

Upvotes: 2

Related Questions