使用update_attributes时,Ruby在Rails上出现ForbiddenAttributesError

时间:2018-12-12 09:45:10

标签: ruby-on-rails ruby postgresql

我正在创建简单的ruby博客应用程序,我正在更新帖子,但显示出此类型错误 error

        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"})

这是工作

3 个答案:

答案 0 :(得分:0)

您应该使用strong parameters,Rails会阻止您为security reasons分配来自外界的未经过滤的参数。

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

# ...

private

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

答案 1 :(得分:0)

属性应列入白名单以进行更新。

下面是代码:

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

        def update
           @post = Post.find(params[:id])
           if @post
              @post.update_attributes(post_params)
              redirect_to post_path, :notice => "you post  has been updated"
           else
              render "edit"
           end
        end

   private

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

答案 2 :(得分:0)

ActiveModel::ForbiddenAttributesError仅在您将未消毒的对象传递给记录更新调用时引发。

@post.update_attributes(params[:post]) # This would be an issue

Post.where(params[:post]) # This would not

@post.update_attributes(post_params) # Neither would this

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