尝试添加新注释时,ActiveModel :: ForbiddenAttributesError

时间:2016-10-03 20:46:57

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

我在app / controllers / comments_controller.rb中有以下代码

class CommentsController < ApplicationController
  def create
    book = Book.find params[:book_id]
    comment = book.comments.new params[:comment]
    comment.save
    flash[:notice] = 'Comment saved'
    redirect_to book_path(book)     
  end
end

我不知道为什么我会在第comment = book.comments.new params[:comment]

收到错误

我尝试将comment = book.comments.new params[:comment]更改为comment = book.comments.new(comment)但是当我点击保存时它没有显示应用程序的评论

还尝试过这样的事情

class CommentsController < ApplicationController
  def create
    book = Book.find params[:book_id]
#    comment = book.comments.new params[:comment]
     comment =  book.comments.new(comment_params)     
    comment.save
    flash[:notice] = 'Comment saved'
    redirect_to book_path(book)     
  end

 def comment_params
   params.require(:comment).permit()
 end

 end

2 个答案:

答案 0 :(得分:1)

此行(btw ()是可选的)

params.require(:comment).permit()

只是意味着您允许分配NO属性,因此错误。

添加属性列表(将它们列入白名单)以便能够分配它们:

params.require(:comment).permit(:name, :title, :other_attribute)

答案 1 :(得分:0)

这个工作

class CommentsController < ApplicationController
  def create
    book = Book.find params[:book_id]
     #comment = book.comments.new params[:comment]
 @comment = book.comments.create!(params.require(:comment).permit!)    
     #comment =  book.comments.new(comment_params)     
    #comment.save
    flash[:notice] = 'Comment saved'
    redirect_to book_path(book)     

end
 end