基本安全原因都強參數的存在和attr_accessible是,有在模型中的某些屬性不應該被允許改變,除非它是你的代碼的明確意圖。
它們之間的細微差別是他們完成工作的觀點。
StrongParameters重點關注用例:考慮到任何條件,可以對每個控制器的動作進行微調以允許或禁止某些參數。總體靈活性。
attr_accessible採取不同的觀點。它不專注於用例,而是專注於角色。因此,例如,根據用戶的角色,某些屬性可以更改或不更改。
使用StrongParameters的方法是應用在帕拉姆哈希require
和permit
關鍵字。
require
指出密鑰必須存在於參數散列中。如果沒有這樣的密鑰,require
將引發異常。
permit
指出允許一個字段。任何不允許的密鑰都將從散列中刪除,因此不會通過批量分配傳遞給模型。
型號
class League
attr_protected :final_price # Nobody can mass-assign the final price
attr_accessible :winner_name, :as => :jury
end
而且控制器
class LeaguesController < ApplicationController
這兩個動作使用StrongParameters
# A common user can create a league
def create
league = League.new(league_params)
league.final_price = 1000
league.save
redirect_to(league)
end
# But only the admin can publish a league
def publish_league
league = League.find(params[:id]
league.update_attributes(league_params_as_admin)
end
這一次使用attr_accessible
def publish_the_winner
league = League.find(params[:id]
# We would expect the current_user.role to return :jury.
league.assign_attributes(params[:league], :as => current_user.role)
end
private
def league_params
params.require(:league).permit(:name)
end
def league_params_as_admin
params.require(:league).permit(:name, :status)
end
end
以我的經驗:
使用強參數的微調的靈活性,什麼屬性可大量分配在每個控制器。
使用無處不在的attr_accesible來確保某些屬性無論如何都不能被批量分配。例如,在Resque Task中,您可以將用戶輸入作爲參數傳遞。您將檢查某些屬性是否使用attr_accesible進行批量分配。
更多信息:
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html
https://github.com/rails/strong_parameters
你可以發佈你的Gemfile嗎?還有你的模型中的代碼? – Agis
@randombits你是否從rails3升級你的項目? – AKovtunov