首页 > 解决方案 > 使用 update_attributes 时 ruby​​ on rails 中的 ForbiddenAttributesError

问题描述

我正在创建简单的 ruby​​ 博客应用程序我正在更新一篇文章,但它显示了这种类型的错误 错误

        def edit
            @post = Post.find(params[:id])
        end

        def update
            @post = Post.find(params[:id])
            if @post
                puts "******************dd*********************"
                puts params[:post]
                puts "**************************************"
                @post.update_attributes(params[:post])


                redirect_to post_path, :notice => "you post  has been updated"
            else
                render "edit"
            end
        end

但是当我使用这个

        @post.update_attributes({"title"=>"2nd", "body"=>"this is second post body", "category_id"=>"2"})

这是工作

标签: ruby-on-railsrubypostgresql

解决方案


您应该使用强参数,Rails 会出于安全原因阻止您分配来自外部世界的未过滤参数。

def update
  # ...
  @post.update_attributes(post_params)
  # ...
end

# ...

private

def post_params
  params.require(:post).permit(:title, :body, :category_id)
end

推荐阅读