我有路线
POST /posts/:post_id/comments(.:format) comments#create
我的评论有“内容”字段。假设我想对我的帖子发表评论。
所以我尝试通过执行此命令的curl 发表评论 curl -X POST -H“内容类型:application/json”-d '{“comment”:“hello”}' http://localhost:3000/posts/2/comments
但是我得到了一个动作控制器:捕获异常
不知道为什么
控制器
# POST /comments
# POST /comments.json
def create
@comment = @post.comments.new(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:comment)
end
编辑:
error in log file
Completed 500 Internal Server Error in 2ms
NoMethodError (undefined method `permit' for "hello":String):
app/controllers/comments_controller.rb:89:in `comment_params'
app/controllers/comments_controller.rb:33:in `create'
编辑: curl -X POST -H“内容类型:application/json”-d '{“comment”:{“comment”:“test”}}' http://localhost:3000/posts/8/comments
为我工作,但我有点困惑为什么当我为我的帖子做类似的卷曲时:
curl -H "Content-Type: application/json" -d '{"title":"funny title","content":"cool stuff", "user_id":2}' localhost:3000/posts
我的帖子参数看起来像这样 params.require(:post).permit(:title, :content, :user_id)
为什么不用在curl哈希中传递帖子就可以工作?
你这里说的是“对于评论对象,允许评论属性”
params.require(:comment).permit(:comment)
所以 Rails 期待类似的东西:
{"comment": {"comment": "hello"}}
如果您想快速修复它 -> 您需要将上述内容用于您的数据。 否则,您需要弄清楚真实评论表单的数据到底是什么样子,并更新您的要求/许可行以匹配该数据
本博客提供了有关调试 Rails 应用程序的指导,该应用程序在尝试使用curl 创建评论时会引发操作控制器问题。 comment_params函数中的No Method错误是作者调查日志文件中问题的主要焦点。检查给定的curl命令后,通过更改curl语法以将注释合并到嵌套散列中解决了该问题。该教育材料阐明了如何排查和解决 Rails API 调用问题。