【发布时间】:2015-02-09 04:06:45
【问题描述】:
我有路线
POST /posts/:post_id/comments(.:format) comments#create
我的评论有“内容”字段。假设我想对我的帖子发表评论。
所以我正在尝试通过 curl 执行此命令发表评论 curl -X POST -H "Content-Type: 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 "Content-Type: application/json" -d '{"comment":{"comment":"test"}}' http://localhost:3000/posts/8/comments
为我工作,但我有点困惑,为什么当我为我的 POST 做类似的 curl 时:
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 哈希中传递帖子就可以工作?
【问题讨论】:
-
嗨 - 如果你有一个异常......这意味着你的应用程序将生成一个堆栈跟踪 - 这对于帮助找出究竟出了什么问题非常有用。您通常会在您的服务器窗口或日志文件中找到它——它大约有 20-40 行各种文件的列表,最顶部有一条错误消息。找到它,然后编辑您的问题并将其全部粘贴到那里,我们可以帮助您找出问题所在。
标签: ruby-on-rails api curl