淺談Rails 4 中Strong Parameters機制
要弄明白Rails 4 中Strong Parameters機制,首先我們要看看Rails3中的Parameters
在 Rails3 中創(chuàng)建或更新 Active Record 對象時,會有 Mass Assignment 安全問題。所以 Model 中需要列一個白名單,聲明哪些屬性可以被 parameter 的數(shù)據(jù)更新。
Rails 3
# kings_controller.rb
def create
#{ name: ‘David', sex:male, age: 31}
@king = King.new(params[:king])
if @king.save
redirect_to @king
else
render 'new'
end
end
# king.rb
class King
attr_accessible :name
end
Rails 4
Rails 4 引入了 Strong Parameters 的機制,Model 不再負責白名單的維護,把過濾非法屬性的職責推給了 Controller。
# kings_controller.rb
def create
# new parameter { name: ‘David' }
@king = King.new(king_params)
if @king.save
redirect_to @king
else
render 'new'
end
end
private
def king_params
# old parameter { name: ‘David', sex:male, age: 31}
# new parameter { name: ‘David' }
params[:king].permit(:name)
end
# king.rb
class King
end
什么是 Strong Parameters?

說白了 Strong Parameter 其是就是一層白名單過濾。
View 層穿過來的數(shù)據(jù)會轉(zhuǎn)化為一個 ActionController::Parameters 對象
過濾老的 ActionController::Parameters 對象,生成一個新的 ActionController::Parameters 對象。
* 只保留白名單屬性
* 實例變量 @permitted 賦為 true
把過濾后的 ActionController::Parameters 對象傳給 model,創(chuàng)建或更新對應的的 ActiveRecord 對象。
可以硬傳給 model,霸王硬上弓嗎?
未經(jīng) Strong Parameter 過濾的 ActionController::Parameters 對象的 @permitted 為 false(過濾后為 true)。如果硬傳給 Model,會報錯 ActiveModel::ForbiddenAttributesError 。
- MyBatis3傳遞多個參數(shù)(Multiple Parameters)
- Pytorch之parameters的使用
- Struts2源碼分析之ParametersInterceptor攔截器
- ECMAScript6函數(shù)剩余參數(shù)(Rest Parameters)
- PowerShell函數(shù)中使用$PSBoundParameters獲取輸入?yún)?shù)列表實例
- PDO版本問題 Invalid parameter number: no parameters were bound
- asp.net Parameters.AddWithValue方法在SQL語句的 Where 字句中的用法
- 基于parameters參數(shù)實現(xiàn)參數(shù)化過程解析
相關(guān)文章
對優(yōu)化Ruby on Rails性能的一些辦法的探究
這篇文章主要介紹了對優(yōu)化Ruby on Rails性能的一些辦法的一些探究,包括避免內(nèi)存密集型的應用和GC等相關(guān)問題的探討,需要的朋友可以參考下2015-11-11
在 Ubuntu 12.04 Server 上安裝部署 Ruby on Rails 應用
本教程只適合 Ubuntu Server 用于部署項目到線上,建議使用同樣的 Ubuntu 版本,以免遇到一些版本不同帶來的問題2014-07-07
Ruby升級后no such file to load -- readline解決辦法
這篇文章主要介紹了Ruby升級后no such file to load -- readline解決辦法,需要的朋友可以參考下2015-04-04

