2014-03-25 2 views
0

저는 이전에 레일즈 4로 마이그레이션했지만 처음에는 "protected_attributes"젬을 사용했습니다.왜 ActiveModel :: ForbiddenAttributesError가 발생합니까?

이제 보석을 제거하고 강력한 매개 변수를 올바르게 사용하고 있다고 생각하지만 다음 오류가 발생합니다. 왜?

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

나는 development.rb에서 config.active_record.mass_assignment_sanitizer 문을 주석 처리하고 난 내 application.rb에는 config.active_record.whitelist_attributes 문이 없습니다.

답변

2

이 작동합니다 :

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

감사 :

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 

이것은 Github에서 * 당신이 강한 매개 변수를 사용할 수있는 방법 ME는 레일 팀에서 보여 * 읽어주십시오. 그것은 효과가있었습니다. 왜 그런가요? –

+0

@steven_noble 왜냐하면 그것이 강한 매개 변수가 작동하기 때문입니다. 특정 params 키를 수동으로 '요구'하고 속성을 허용해야합니다. –

+1

또한이 코드는 create 메소드에 있어서는 안됩니다. 이전 작업의 개인 메서드에서 범주에 허용 된 특성을 사용하여 개인 메서드를 호출해야합니다. –

0

이 레일을 강한 매개 변수를 사용의 좋은 사용 사례입니다. 상상, 당신은 요리 모델을 가지고 있고, 그것은 이름, 간략한 설명관련 그림 있습니다. 따라서 요리 컨트롤러의 강한 매개 변수이 이런 방식으로 사용됩니다. https://github.com/rails/strong_parameters

관련 문제