最近总是遇到这个问题,因为我看的资料都是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
错误解决!