0

我在玩Rails 3.2.13和strong_parameters gem。我想知道當我在開發中進行測試時,是否應該從ActiveModel::ForbiddenAttributes獲得異常提示?Rails 3.2.13和strong_parameters例外

我的崗位模型具有:title:content但如果我從許可證刪除:title,我沒有得到一個錯誤,但我得到重定向回用閃光燈通知的編輯頁面,所以它的保存記錄。儘管如此,它並沒有改變:title。這是默認行爲嗎?

def post_params 
    params.require(:post).permit(:content) 
    end 

我想知道如果我需要做些別的事情來獲取引發的異常。

的Gemfile:

# Gemfile 
gem 'rails', '3.2.13' 
gem "strong_parameters" 

應用程序配置:

# config/application.rb 
config.active_record.whitelist_attributes = false 

Post模型:

# post.rb model 
class Post < ActiveRecord::Base 
    include ActiveModel::ForbiddenAttributesProtection 
end 

柱控制器:

# post_controller.rb 
class PostsController < ApplicationController 

    def update 
    @post = Post.find(params[:id]) 
    if @post.update_attributes(post_params) 
     redirect_to edit_post_path(@post), flash { success: "Post updated" } 
    else 
     render "edit" 
    end 
    end 


    private 

    def post_params 
    params.require(:post).permit(:title, :content) 
    end 
end 

回答

4

默認配置是在開發和測試環境中記錄異常,甚至不在生產環境中記錄異常。所以你看到的是正常的行爲,這項任務沒有成功。

要引發異常,您需要在所需的環境中更改默認值。 例如,配置/環境/ development.rb:

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

希望幫助,

相關問題