【问题标题】:ruby on rails - ActiveModel::ForbiddenAttributesError in CommentsController#create [duplicate]ruby on rails - CommentsController#create 中的 ActiveModel::ForbiddenAttributesError [重复]
【发布时间】:2013-11-20 12:48:39
【问题描述】:
ActiveModel::ForbiddenAttributesError
Extracted source (around line #3):

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

Rails.root: C:/Users/ManU/Desktop/quick_blog  
Application Trace | Framework Trace | Full Trace

app/controllers/comments_controller.rb:4:in `create'

我应该做些什么来处理这个错误.....

【问题讨论】:

  • 能否再次确认您使用的是 Rails3 还是 4?您已将此标记为 rails3。这个错误对于使用 rails 4 的新手来说很常见
  • 我会说你应该先谷歌,和/或阅读文档,因为这个话题被广泛讨论。
  • 是的,我正在使用 rails4..???我现在应该做什么......

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

我遇到了同样的错误,出于某种原因,他们删除了评论创建行上的 .permit 部分。如果你使用原版:

@comment = @post.comments.create(params[:comment].permit(:commenter, :body))

而不是新的:

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

它工作正常。所以该文件最终看起来像:

class CommentsController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    #@comment = @post.comments.create(params[:comment])
    @comment = @post.comments.create(params[:comment].permit(:commenter, :body))
    redirect_to post_path(@post)
  end

  def destroy
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post)
  end

end

【讨论】:

    【解决方案2】:

    希望这行得通! (我遇到了同样的错误,以下更改对我有用)

    def create
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create(params[:comment].permit(:commenter, :body))
    redirect_to post_path(@post)
    end
    

    【讨论】:

      【解决方案3】:

      ForbiddenAttributesError 与Strong Parameters 相关

      要么您在 Rails3 应用程序中安装了 gem,要么您错过了标记问题,而您使用的是 Rails4,gem 是默认提供的。

      无论哪种方式,使用强参数,参数检查都会离开模型并传递给控制器​​。

      以前在模型中会有 attr_accessible :foo, :bar 这样的东西,现在你需要有类似的东西

      def comment_params
        params.permit(:foo, :bar)
      end
      

      在控制器中,然后调用Comment.create!(comment_params)

      【讨论】:

      • 请同时指定路径..我要编辑的地方...这是我的应用程序位置 C:\Users\ManU\Desktop\quick_blog
      • 对于我告诉你的,你应该查看应该在 quick_blog/app/models/comment.rb 和 quick_blog/app/controllers/cmets_controller.rb 中的 Comment 模型和控制器
      猜你喜欢
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多