Ruby on rails 为什么我会得到一个ActiveModel::ForbiddenAttribute错误
不久前我迁移到Rails 4,但最初我使用了“protected_attributes”gem 现在,我已经删除了那个gem,我认为我正确地使用了强参数,但是我得到了以下错误。为什么?Ruby on rails 为什么我会得到一个ActiveModel::ForbiddenAttribute错误,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,不久前我迁移到Rails 4,但最初我使用了“protected_attributes”gem 现在,我已经删除了那个gem,我认为我正确地使用了强参数,但是我得到了以下错误。为什么? From: /Users/steven/Dropbox/Testivate/app/controllers/categories_controller.rb @ line 21 CategoriesController#create: 20: def create => 21: bindin
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>)>
From:/Users/steven/Dropbox/Testivate/app/controllers/categories_controller.rb@line 21 CategoriesController#创建:
20:def创建
=>21:binding.pry\u远程
22:@category=category.new(参数[:category])。许可证(:名称)
23:flash[:notice]=“类别已成功创建。”如果@Category.save
24:使用(@category)响应_
25:完
[1] 撬动(#)>参数
=>{“utf8”=>“✓",
“类别”=>{“名称”=>“衣服”},
“提交”=>“创建类别”,
“操作”=>“创建”,
“控制器”=>“类别”}
[2] pry(#)>@category=category.new(params[:category]).permit(:name)
ActiveModel::禁止属性错误:ActiveModel::禁止属性错误
来自/Users/steven/.rvm/gems/ruby-2.1.0/gems/activemodel-4.0.2/lib/active\u model/problemed\u attributes\u protection.rb:21:in `用于批量分配的消毒'
[3] 撬动(#)>
我已经注释掉了development.rb
中的config.active\u record.mass\u assignment\u sanitarizer
语句,并且在我的application.rb
中没有config.active\u record.whitelist\u attributes
语句,这应该可以:
@category = Category.new(params.require(:category).permit(:name))
这是一个很好的使用Railsstrong参数的用例。想象一下,您有一个烹饪模型,它有一个名称,简要描述和一个关联的Pic。因此,您的烹饪控制器将以这种方式使用它的strong参数
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
class-CuisineController
来自Rails团队的Github*READ ME*演示了如何使用strong参数:
@steven_noble只是因为强参数就是这样工作的。您需要手动“要求”特定的参数密钥并允许其中的属性。此外,此代码不应出现在您的create方法中。您应该在before操作中为私有方法中的Category调用具有允许属性的私有方法。