CommentsController中的ActiveModel :: ForbiddenAttributesError #create

时间:2013-11-08 14:12:25

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

::加载ActiveModel ForbiddenAttributesError 提取的来源(第3行):

  1. def create
  2. @post = Post.find(params [:post_id])
  3. @comment = @ post.comments.create!(params [:comment])
  4. redirect_to @post
  5. Rails.root:C:/ Users / ManU / Desktop / quick_blog 应用程序跟踪|框架跟踪|完整跟踪

    app / controllers / comments_controller.rb:4:在'create'

    我应该做些什么来处理这个错误..... 请给我解决路径......我没有事先知道这个......

2 个答案:

答案 0 :(得分:8)

您似乎正在使用rails 4跟踪pre rails 4.0教程。您现在需要使用强params。

http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

还有一个应该有用的railscast。

@comment = @post.comments.create!(params.require(:comment).permit!) 


@comment = @post.comments.create!(params.require(:comment).permit(:comment_text,:link))

第一个允许允许所有参数,后者只允许接受comment_textlink

答案 1 :(得分:1)

如果系统正在抛出ActiveModel :: ForbiddenAttributesError,这意味着您必须使用 strong_parameters gem,或者您的rails应该具有大于4的版本,在这种情况下,strong_parameters gem已包含在该版本中。在这种情况下,您可以在 application_controller.rb 上添加以下代码,以摆脱此错误。

before_filter do
  resource = controller_name.singularize.to_sym
  method = "#{resource}_params"
  params[resource] &&= send(method) if respond_to?(method, true)
end