我刚刚迁移到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
语句。
答案 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