ActiveModel::ForbiddenAttributesError

2019-07-09 15:15发布

问题:

i've been following rails guide on creating and mounting an engine here.Created blog post and when i tried to comment ,it returned "ActiveModel::ForbiddenAttributesError in Blorgh::CommentsController#create " error. Comment controller

    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

and here is comment model

 module Blorgh
  class Comment < ActiveRecord::Base

  end
end

how to resolve the issue?

回答1:

I guess you are using rails 4. You need to mark all the required parameters here it goes :

   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

hope this link helps...



回答2:

I had the same error. So if you disect the params hash it easy to see the nested comment params with text key. Seems the tutorial is for Rails 3, so for the rails 4 way with trusted params the changes needed is to add the comment_params method as below.

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