rails中ActiveModel::ForbiddenAttributesError的解决方案(新)
来源:互联网 发布:淘宝直通车有什么用 编辑:程序博客网 时间:2024/05/21 18:47
最近总是遇到这个问题,因为我看的资料都是Rails3.2的,但是用的开发环境是4.0的,而4.0增加了一些安全措施
这类错误大多出现在new或者create两个action中
- def create
- #params.permit!
- @post = Post.find(params[:post_id])
- @comment = @post.comments.new(params[:comment])
- @comment.save
- redirect_to @post
- end
错误出现在:
- @comment = @post.comments.new(params[:comment])
以前我的处理方法很粗暴,就是直接在方法的前面加上params.permit! 见上述代码注释的那行,但这样做不太安全, 原因见下面
因为初始化整个 params Hash 是十分危险的,一旦初始化就会把用户提交的所有数据传递给 User.new 方法。假设除了前述的属性,User 模型还包含 admin 属性,用来标识网站的管理员。(我们会在 9.4.1 节加入这个属性。)要把这个属性设为 true,就要在 params[:user] 中包含 admin='1',这个过程可以轻易的使用 curl 这种命令行 HTTP 客户端实现。结果是,把整个 params 传递给 User.new 网站的任一用户都可以在请求中包含 admin='1' 来获取管理员权限。
基于这种状况,我加上params.permit!
又回到了4.0之前的情况。正确的处理是这样的,我们之允许需要的参数传进来将params[:comment]改为comment_params 并为comment_params建立一个私有方法
- class CommentsController <ApplicationController
- def new
- end
- def create
- #params.permit!
- @post = Post.find(params[:post_id])
- @comment = @post.comments.new(comment_params)
- @comment.save
- redirect_to @post
- end
- private
- def comment_params
- params.require(:comment).permit(:post_id , :content)
- end
- end
错误解决!
0 0
- rails中ActiveModel::ForbiddenAttributesError的解决方案(新)
- rails中ActiveModel::ForbiddenAttributesError的解决方案(新)
- rails中ActiveModel::ForbiddenAttributesError的解决方案
- rails 4.0 中出现 ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError 错误
- ruby on rails出现的问题ActiveModel::ForbiddenAttributesError
- ActiveModel::ForbiddenAttributesError
- 在rails 4.0 中 使用strong_parameters 来避免 ActiveModel::ForbiddenAttributesError 错误
- 在rails 4.0 中 使用strong_parameters 来避免 ActiveModel::ForbiddenAttributesError 错误
- Rails4版本的ActiveModel::ForbiddenAttributesError错误
- ActiveModel
- Rails中Delete请求无法使用的解决方案
- 【rails】spork测试中出现ActiveRecord::ConnectionNotEstablished的解决方案
- [rails]Spork中出现“Could not start Spork server for RSpec”的解决方案
- Google的新主意:JavaScript on Rails
- 基于rails的schedule网站开发(19):新的远程仓库,新的部署,远程分支使用
- Rails中 accepts_nested_attributes_for 的用法
- Rails中session的使用方法
- rails中session的作用
- NYOJ47 过河问题
- UIEdgeInsetsMake详细讲解
- discuz 添加创始人
- 3.17
- 微软妥协Android?向该平台推开源Office 365 SDK
- rails中ActiveModel::ForbiddenAttributesError的解决方案(新)
- jQuery.map使用方法
- Android Volley网络请求框架 实现post方法并带Map参数上传
- RAM和ROM的区别
- 如何判断电话摘机
- js获取html元素style
- Partially written block *** detected解决方案
- stringsteram用法
- VC2010 使用teechart绘制风向玫瑰图