Rails 5.0错误:ActiveModel :: ForbiddenAttributesError

时间:2016-11-03 23:00:27

标签: ruby-on-rails ruby

我正在尝试在我的网络应用程序上发布可从浏览器更新的博客文章,但是当我在编辑中单击更新时,我收到此错误: ::加载ActiveModel ForbiddenAttributesError

pot_controller第33行中的

错误:

if @ post.update_attributes(params [:post])

这是我的edit.html.erb代码:

<h1>Edit Post</h1>
<%= form_for @post do |f| %>
    <p>
        <%= f.label :title %><br />
        <%= f.text_field :title %><br />
    </p>
    <p>
        <%= f.label :body %><br />
        <%= f.text_field :body %><br />
    </p>
    <p>
        <%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, {:include_blank => "Select One"} %><br />
    </p>
    <p>
        <%= f.submit "Update post" %>
    </p>
<% end %>
<%= link_to "Go Back", post_path %>

这是我的posts_controller.rb代码:

class PostsController < ApplicationController
    def index
        @posts = Post.find(4,5)
    end

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

    def new
        @post = Post.new
        @category = Category.all

    end

    def create
        @post = Post.new(params[:post])
        if @post.save
            redirect_to posts_path, :notice => "Your post has been saved"
        else
            render "new"
        end

    end

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

    end

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

    end

    def destroy
        @post = Post.find(params[:id])
        @post.destroy
        redirect_to posts_path, :notice => "Your post has been deleted"
    end

end

希望并感谢任何人都可以提供帮助。最好,M

1 个答案:

答案 0 :(得分:2)

强参数

Rails默认使用名为Strong Parameters的安全机制。其目的是确保只能通过用户提交的表单更新某些字段。

@post.update_attributes(params[:post])是一种旧式语法,不适用于强参数。

更新的惯例如下

class PostsController
  def update
    # ...
    @post.update(post_params) # instead of passing params[:post] directly, you pass it a strong parameters whitelist (see below)
  end

  def post_params
    # we construct a strong parameters whitelist below
    # require(:post) means that the `params` hash MUST contain a :post key
    # permit(:title, :body, ...) = here we enumerate the attributes which we will accept from the form parameters; it acts as a whitelist
    params.require(:post).permit(:title, :body, ...) 
  end
end

如果使用rails g scaffold,您可以看到使用强参数的控制器示例。

不要这样做:要默认禁用强参数,可以设置以下配置值

config.active_record.whitelist_attributes = false

我把它包括在内是为了完整性&#39;但是,您不应该这样做,因为它会不必要地为您的代码引入安全漏洞。

其他资源