【问题标题】:Params Error (ActiveModel::ForbiddenAttributesError)参数错误 (ActiveModel::ForbiddenAttributesError)
【发布时间】:2014-03-08 04:53:09
【问题描述】:

我在“@comment = @post.cmets.build(params[:comment])”中得到一个“ActiveModel::ForbiddenAttributesError in CommentsController#create”和高亮显示

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(params[:comment])

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @post, notice: 'Comment was successfully created.' }
        format.json { render action: 'show', status: :created, location: @comment }
      else
        format.html { render action: 'new' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

在教程视频中,编码员将其放入并完美运行,但当我发布此视频时,它会出错。我检查了代码,似乎看不出有什么问题。提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby params


    【解决方案1】:

    查看错误,我假设您必须使用 Rails 4。Rails 4 中引入了强参数。请参阅Strong Parameters 参考这里。

    替换

     @comment = @post.comments.build(params[:comment]) 
    

     @comment = @post.comments.build(comment_params) 
    

    在控制器中添加私有方法,如下所示:

      def comment_params
        params.require(:comment).permit(:attr1, :attr2,...)
      end
    

    在哪里 :attr1, :attr2 是 Comment 模型的属性名。

    【讨论】:

    • +1.. 你是对的。类似的帖子 - stackoverflow.com/questions/17335329/…
    • 我确实用@comment = @post.cmets.build(comment_params) 替换了它,但最终得到了另一个错误,“NameError in Comments#index”与“" 我知道这是一条有效路径,因为 rake routes ):
    • 您能否在问题中发布错误堆栈跟踪。同时分享索引操作。
    • 啊,我看了更深,经过反复试验找到了解决方案。谢谢您的帮助!它修复了错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多