rails 4 ActiveModel :: ForbiddenAttributesError

我尝试使用rails 4进行简单的创建

我的控制器:

class AdsController < ApplicationController def new @ad = Ad.new end def create @ad = Ad.new(params[:ad]) @ad.save end def show @ad = Ad.find(params[:id]) end def index @ads = Ad.first(3) end private def ad_params params.require(:ad).permit(:title, :price, :description) end end 

形成:

  

从我的角度来看它没问题,但是我得到了这个错误ActiveModel::ForbiddenAttributesError我做错了什么?

更新:

我的问题是在创建操作中将错误的值传递给新方法:解决方案是将ad_params传递给它

我建议跳过更新,以便你的代码工作

您的问题可能不在您的控制器中,而是您的模型:使用以下标记检查您的属性是否可访问

 attr_accessible :title, :price, :description 

Rails 4确实与我理解的有点不同,这个以前的SO答案提供了一些很好的链接: 如何在Rails 4中使用attr_accessible?

每当您从数据库访问内容时,都需要使用attr_accessible / Strong Params。

更新

哦,年轻,并没有意识到Rails 4使用强大的参数。 我知道OP已经解决了他原来的问题,但我要纠正这个问题,所以它实际上可以用作正确的答案。

这将是一个控制器级问题,因为Rails 4要求您将控制器中的属性列入白名单。

 Ad.create(params[:ad].require(:ad).permit(:title, :price, :description)) 

大多数情况下,您将在创建和更新操作中允许相同的参数,因此最好将其移动到控制器内的自己的方法中。

 Ad.create(ad_params) def ad_params params.require(:ad).permit(:title, :price, :description) end 

正如OP在他的评论中指出的那样,他实施的allowed_pa​​rams方法并未从许可证中调用。

我也面临同样的问题,工作了6个小时,终于得到了解决方案。

试试这个代码,它会对你有所帮助! 在Rails 4中,添加了此function以便以不同方式处理创建。

 def new @ad = Ad.new end def create @ad = Ad.create(ad_params) @ad.save end private def ad_params params.require(:ad).permit(:title, :price, :description) end 

在添加params.permit之前新增广告!

  def create params.permit! @ad = Ad.new(params[:ad]) @ad.save end 

你的应该是这样的:

 def new @ad = Ad.new(params[:ad].permit(:title, :price, :description)) end 

我看起来像这样:

 def create @about = About.new(params[:about].permit(:introduction, :description)) respond_to do |format| if @about.save format.html { redirect_to @about, notice: 'About was successfully created.' } format.json { render action: 'show', status: :created, location: @about } else format.html { render action: 'new' } format.json { render json: @about.errors, status: :unprocessable_entity } end end end