::加载ActiveModel ForbiddenAttributesError

时间:2013-10-22 05:22:31

标签: ruby-on-rails rubygems

我一直在关注创建和安装引擎here的rails指南。创建了博客帖子,当我试图发表评论时,它返回了“Blorgh :: CommentsController #create”中的“ActiveModel :: ForbiddenAttributesError”错误。 评论控制器

    require_dependency "blorgh/application_controller"

module Blorgh
  class CommentsController < ApplicationController
    def create
      @post = Post.find(params[:post_id])
      @comment = @post.comments.create(params[:comment])
      flash[:notice] = "Comment has been created!"
      redirect_to posts_path
    end
  end
end

这里是评论模型

 module Blorgh
  class Comment < ActiveRecord::Base

  end
end

如何解决问题?

2 个答案:

答案 0 :(得分:3)

我猜你正在使用rails 4.你需要标记所有必需的参数 在这里:

   def create
      @post = Post.find(params[:post_id])
      @comment = @post.comments.create(post_params)
      flash[:notice] = "Comment has been created!"
      redirect_to posts_path
    end

    def post_params
      params.require(:blorgh).permit(:comment)
    end

希望 this link 有帮助......

答案 1 :(得分:0)

我有同样的错误。因此,如果您使用params散列,则很容易看到带有文本键的嵌套注释参数。看起来本教程适用于Rails 3,因此对于带有受信任的params的rails 4方式,所需的更改是添加如下的comment_params方法。

Parameters:

  {"utf8"=>"✓",
  "authenticity_token"=>"uOCbFaF4MMAHkaxjZTtinRIOlpMj2QSOYf+Ugn5EMUI=",
  "comment"=>{"text"=>"asfsadf"},
  "commit"=>"Create Comment",
  "post_id"=>"1"}

    def create
      @post = Post.find(params[:post_id])
      @comment = @post.comments.create(comment_params)
      flash[:notice] = "Comment has been created!"
      redirect_to posts_path
    end

    private

      # Only allow a trusted parameter "white list" through.
      def comment_params
        params.require(:comment).permit(:text)                
      end