rails中ActiveModel::ForbiddenAttributesError的解决方案(新)
2013-09-28 16:13
363 查看
最近总是遇到这个问题,因为我看的资料都是Rails3.2的,但是用的开发环境是4.0的,而4.0增加了一些安全措施
这类错误大多出现在new或者create两个action中
错误出现在:
以前我的处理方法很粗暴,就是直接在方法的前面加上params.permit! 见上述代码注释的那行,但这样做不太安全, 原因见下面
基于这种状况,我加上params.permit!
这类错误大多出现在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
错误解决!
相关文章推荐
- rails中ActiveModel::ForbiddenAttributesError的解决方案(新)
- rails中ActiveModel::ForbiddenAttributesError的解决方案
- rails 4.0 中出现 ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError 错误
- ruby on rails出现的问题ActiveModel::ForbiddenAttributesError
- 在rails 4.0 中 使用strong_parameters 来避免 ActiveModel::ForbiddenAttributesError 错误
- ruby on rails出现的问题ActiveModel::ForbiddenAttributesError
- rake abort! Rails mysql2 error: “rake aborted! Please install the mysql2 adapter…”解决方案
- ActiveModel::ForbiddenAttributesError
- axis2.AxisFault: Transport error: 403 Error: Forbidden 解决方案
- 【Rails】Sass::SyntaxError in StaticPages#home错误的解决方案
- 提升Ruby on Rails性能的几个解决方案
- oracle:ERROR:ORA-12162: TNS:net service name is incorrectly specified解决方案
- HTTP 错误 500.21 - Internal Server Error 解决方案
- AAPT err... ERROR: Unable to open PNG file的解决方案
- 【爬虫 | 报错】urllib.error.HTTPError: HTTP Error 403: Forbidden
- Mac下编译在windows创建的项目TypeError: Cannot read property 'message' of undefined...解决方案
- LLVM ERROR: Program used external function '___dso_handle' which could not be resolved!的解决方案
- VC++ Unable to register this add-in because its DllRegisterServer returns an error 解决方案
- java.lang.OutOfMemoryError: Java heap space解决方案
- response.sendfile() fails with Error: Forbidden