Rails 5.0错误:ActiveModel::ForbiddenAttributesError
Rails 5.0错误:ActiveModel::ForbiddenAttributesError
我正试图让我的网页应用程序中的博客文章可以从浏览器进行更新,但是当我在编辑表单中点击更新时,出现以下错误:\nActiveModel::ForbiddenAttributesError\npots_controller的第33行出现错误:\nif @post.update_attributes(params[:post])\n以下是我的edit.html.erb代码:\n
编辑文章
<%= form_for @post do |f| %> <%= f.label :title %> <%= f.text_field :title %> <%= f.label :body %> <%= f.text_field :body %> <%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, {:include_blank => "选择一个"} %> <%= f.submit "更新文章" %> <% end %> <%= link_to "返回", post_path %>
\n以下是我的posts_controller.rb代码:\n
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 => "你的文章已保存" 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 => "你的文章已更新" else render "edit" end end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to posts_path, :notice => "你的文章已删除" end end
\n希望有人能帮到我。谢谢!最好,M
Rails 5.0 Error: ActiveModel::ForbiddenAttributesError
在Rails中,默认使用了一种名为Strong Parameters的安全机制。其目的是确保只有特定的字段可以通过用户提交的表单进行更新。
.update_attributes(params[:post])
是一种旧式的语法,不适用于Strong Parameters。
更新的约定如下:
class PostsController def update # ... .update(post_params) # 不再直接传递 params[:post],而是传递一个Strong Parameters白名单(见下文) end def post_params # 下面我们构造一个Strong Parameters白名单 # require(:post) 表示 `params` 哈希必须包含一个 :post 键 # permit(:title, :body, ...) = 这里我们罗列了我们将从表单参数中接受的属性;它作为一个白名单 params.require(:post).permit(:title, :body, ...) end end
如果你使用 rails g scaffold
可以看到一个使用Strong Parameters的控制器示例。
不要这样做:为了禁用Strong Parameters的默认使用,你可以设置以下配置值:
config.active_record.whitelist_attributes = false
我包括这个配置是为了完整性的缘故,但你不应该这样做,因为它会不必要地引入安全漏洞到你的代码中。