13

我有点失落。我收到 Rails 4 错误:ActiveModel::ForbiddenAttributesError。我明白这意味着我需要允许物品通过,我已经这样做了,但我一定错过了一些东西。

评论控制器:

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

    private
        # Never trust parameters from the scary internet, only allow the white list through.
        def comment_params
            params.require(:comment).permit(:post_id, :comment, :body)
        end

end

创建评论迁移

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.references :post
      t.text :body

      t.timestamps
    end
  end

  def self.down
    drop_table :comments
  end  
end

我在这里想念什么?如果您需要查看任何其他代码,请告诉我。

谢谢!

4

1 回答 1

32

代替

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

你要

@comment = @post.comments.create!(comment_params)

您在没有使用允许的属性的情况下完成了所有艰苦的工作!

于 2013-09-08T02:32:37.683 回答