【问题标题】:Rails 5.0 Error: ActiveModel::ForbiddenAttributesError [duplicate]Rails 5.0 错误:ActiveModel::ForbiddenAttributesError [重复]
【发布时间】:2017-03-17 16:42:03
【问题描述】:

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

pots_controller 第 33 行错误:

如果@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

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

强参数

Rails 默认使用称为强参数的安全机制。其目的是确保只有某些字段可以通过用户提交的表单进行更新。

@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

为了完整起见,我将其包含在内,但是您不应该这样做,因为它会不必要地为您的代码引入安全漏洞。

其他资源

【讨论】:

    猜你喜欢
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2013-11-20
    相关资源
    最近更新 更多