为什么我得到一个ActiveModel :: ForbiddenAttributesError

时间:2014-03-25 09:17:40

标签: ruby-on-rails ruby-on-rails-4

我刚刚迁移到Rails 4但最初我使用的是" protected_attributes"宝石。

现在,我已删除了该宝石,我认为我正确使用了强大的参数,但我收到了以下错误。为什么呢?

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>)> 

我在config.active_record.mass_assignment_sanitizer中注释了development.rb语句,而config.active_record.whitelist_attributes中没有application.rb语句。

2 个答案:

答案 0 :(得分:2)

这应该有效:

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

答案 1 :(得分:0)

这是使用Rails 强参数的一个很好的用例。想象一下,你有一个菜系模型,它有一个名称一个简要描述和一个相关图片。因此,您的烹饪控制器将以这种方式使用强参数

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

来自 Rails团队 Github * READ ME *展示了如何使用强参数https://github.com/rails/strong_parameters