大家好,我在 generate 一个 controller 之后在里面添加代码
def create
@event = Event.new(params[:event])
@event.save
redirect_to :action => :index
end
想实现添加新条目的功能,可是系统提示
ActiveModel::ForbiddenAttributesError
Extracted source (around line #9):
end
def create
@event = Event.new(params[:event])
@event.save
redirect_to :action => :index
不知道是哪里出了问题呢?
昨天升级 Rails4.0 也遇到了这样的问题,只需要在 create 之前加上 params.permit! 就可以了。 详细可以看 http://edgeapi.rubyonrails.org/classes/ActionController/Parameters.html
Rails 4 使用的是 Stong paramaters. 不需要再使用 Attr_accessible 了。 @zfben 这个方法不建议使用。 参考代码
class ProductsController < ApplicationController
def create
@product = Product.new(product_params)
if @product.save
redirect_to @product, notice: 'Product was successfully created.'
else
render action: 'new'
end
end
private
def product_params
params.require(:product).permit(:name, .... :category)
end
end
#14 楼 @autumnwolf ,我试了你的方法,rails4 下可用~然后有几个问题:
params.permit!
的考虑是什么?全放开不安全?补充下:rails 4.0 中出现 ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError 错误 时 则 需要 方法里面加上 params.permit! 如下: def create params.permit! # render plain: params[:article].inspect @article = Article.new(params[:article])
@article.save redirect_to @article end