2

我一直在关注有关在此处创建和安装引擎的 Rails 指南。创建的博客文章当我尝试发表评论时,它返回“ActiveModel::ForbiddenAttributesError in Blorgh::CommentsController#create”错误。评论控制器

    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

如何解决问题?

4

2 回答 2

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

希望这个链接有帮助...

于 2013-10-22T05:37:09.303 回答
0

我有同样的错误。因此,如果您剖析参数哈希,很容易看到带有文本键的嵌套注释参数。似乎本教程适用于 Rails 3,因此对于具有受信任参数的 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
于 2014-01-20T01:41:41.087 回答