attr_accessible、attr_protected这两个方法最后可用的版本为rails3.2.13,用于在对model进行大量赋值时,通过指定白名单(attr_accessible)或黑名单(attr_protected)的方式,确保安全性。 attr_accessibleh和attr_protected区别的详细说明。
在rails4中,对大量赋值的控制提升到了controller层,采用强参的方式进行限制,故这两个方法被废除。
class PeopleController < ActionController::Base # This will raise an ActiveModel::ForbiddenAttributes exception # because it's using mass assignment without an explicit permit # step. def create #可以指定params.permit!强制允许大量赋值,但为了系统安全性,需要参照update的处理方式,列出可以通过大量赋值(mass assignment)更改属性的白名单列表。 params.permit! Person.create(params[:person]) end # This will pass with flying colors as long as there's a person key # in the parameters, otherwise it'll raise a # ActionController::ParameterMissing exception, which will get # caught by ActionController::Base and turned into that 400 Bad # Request reply. def update person = current_account.people.find(params[:id]) person.update_attributes!(person_params) redirect_to person end private # Using a private method to encapsulate the permissible parameters # is just a good pattern since you'll be able to reuse the same # permit list between create and update. Also, you can specialize # this method with per-user checking of permissible attributes. def person_params #列举白名单列表 params.require(:person).permit(:name, :age) end end因为手上的项目需要从Rails3.2升级到Rails4.0,为了进行平滑升级,可以指定配置
config.action_controller.permit_all_parameters = true允许Rails4+对大量赋值的应用,另外,为了保证系统安全性,对于安全性要求高的业务场景,需要通过指定白名单的方式进行赋值。