2013-05-14 11 views
4

使用Ruby 1.9.3,Rails的3.2.13,Strong_parameters 0.2.1:Strong_parameters不工作

我也跟着教程和railscasts種種跡象顯示,但我不能讓strong_parameters工作。它應該是非常簡單的東西,但我看不出錯誤在哪裏。

配置/初始化/ strong_parameters.rb:

ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection) 

配置/ application.rb中

config.active_record.whitelist_attributes = false 

應用/模型/ product.rb

class Product < ActiveRecord::Base 
end 

應用程序/控制器/ products_controller .rb:

class ExpedientesController < ApplicationController 
    ... 
    def create 
    @product = Product.new(params[:product]) 
    if @product.save 
     redirect_to @product 
    else 
     render :new 
    end 
    end 
end 

這會引發Forbidden Attributes異常,如預期的那樣。但是,當我移動到:

... 
    def create 
    @product = Product.new(product_params) 
    # and same flow than before 
    end 
    private 
    def product_params 
    params.require(:product).permit(:name) 
    end 

然後,如果我去的方式,並輸入「姓名:產品1」和「顏色:紅色」不發生異常;新產品保存在數據庫中,沒有顏色,但名稱正確。

我在做什麼錯?

回答

6

已解決。

默認情況下,不允許使用的屬性會自動失敗,並且所提交的屬性將被過濾掉並被忽略。在開發和測試環境中,錯誤也會被記錄下來。

要更改默認的行爲,例如在開發環境: 配置/環境/ development.rb:

# Raises an error on unpermitted attributes assignment 
    config.action_controller.action_on_unpermitted_parameters = :raise # default is :log 

說實話,在GitHub的倉庫解釋的很清楚。

+0

有一些教程,如[this one](http://guides.rubyonrails.org/getting_started.html),依賴於默認的':raise',這很容易混淆。感謝您解決這個問題。 – 2013-08-20 08:30:36