关于Rails 4 strong parameter 初步理解
2013-07-12 16:08
309 查看
Rails 4废除了之前的attr_accessible机制,为了安全起见,使用了新的strong parameter。写代码遇到点小问题,简单了解一下。官方教程 http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters
这段代码是教程中的例子,看内容不难理解的是,类定义了一个私有方法来决定哪些参数可以被允许,不在白名单中的参数都将被过滤掉。
关于
Permitted Scalar Values
对于如下代码:
如果其中的:id 对应的参数在白名单中,定义scalar方法如下:
其中列表中的键就是被允许的键,如果想讲所有id都列入白名单,则:
这样的话log_entry 所有子键都讲被允许。
class PeopleController < ActionController::Base # This will raise an ActiveModel::ForbiddenAttributes exception # because it's using mass assignment without an explicit permit # step. def create 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
这段代码是教程中的例子,看内容不难理解的是,类定义了一个私有方法来决定哪些参数可以被允许,不在白名单中的参数都将被过滤掉。
关于
Permitted Scalar Values
对于如下代码:
params.permit(:id)
如果其中的:id 对应的参数在白名单中,定义scalar方法如下:
params.permit(id: [])
其中列表中的键就是被允许的键,如果想讲所有id都列入白名单,则:
params.require(:log_entry).permit!
这样的话log_entry 所有子键都讲被允许。
相关文章推荐
- 关于copy,weak,strong的一些理解
- 关于REST架构风格的初步理解
- 关于协程的初步理解
- 关于NP问题的初步理解
- ruby on rails 关于微信企业号回调模式初步验证通过后再次签名验证失败的解决
- 关于NP问题的初步理解
- 关于对多项式的两种表示法的初步理解
- 关于二进制的原码,反码和补码的问题初步理解
- 关于用户态和内核态的初步理解
- 关于递归的初步理解
- 关于ViewPager的初步理解
- 关于JSP乱码问题的初步理解和解决
- 关于版本管理的一些初步理解
- 关于有理式部分分式化解的初步理解
- 关于信号三种处理方式初步理解!
- 我关于KMP算法的初步理解
- 关于bag of words 的初步理解
- 关于ThreadLocal的初步理解
- 关于抽象类和接口的初步理解
- 关于单点登录【SSO】的初步理解