我是rails的新手,并开始使用guides.rubyonrails.org,现在我遇到创建记录的问题。
我尝试发送这个json: { " title":" someTitle", " text":" someText" }
要 http://www.justatest/articles.json
我的模型只将此标题和文本字段定义为属性。
也设置了路线。我的控制器创建方法看起来像这样:
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
我在执行请求时已将POSTMAN设置为方法POST但我收到此错误消息: ActionController的:: ParameterMissing 在ArticlesController #create中 param丢失或值为空:文章
答案 0 :(得分:2)
我相信json需要像:
{ article: { title: "someTitle", text: "someText" } }
方法article_params
尝试找到名为article
的密钥,而您的json没有。
答案 1 :(得分:2)
为了使其正常工作,您必须将ContentType标头设置为“application / json”,以及用于创建记录的相关字段。
收到此请求后,Rails会将标头识别为JSON,然后将JSON解析为我们都知道并喜爱的“params”。
这是一个处理此问题的link some of the source in Rails。