我在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
答案 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