我正在Rails 4.2中使用REST API,我想遵守JSON API格式。我的参数是这样的:
{
"data":{
"type": "articles",
"id": "1",
"attributes": {
"title": "this is title",
"description": "This is description"
}
}
我试图为这样的强参数编写方法:
def article_params
params.require(:data).permit(:id, attributes: [:title, :description])
end
但是当我尝试执行
Article.update_attributes(article_params)
时,它会显示title and description parameters not permitted
[我的文章模型具有标题和描述]。你能帮助我吗?
最佳答案
处理JSONAPI参数与处理常规Rails参数哈希仅略有不同:
class ArticlesController < ApiController
before_filter :set_article, only: [:show, :edit, :update, :destroy]
# POST /api/v1/articles
def create
@article = Article.new(article_attributes)
# ...
end
# PATCH /api/v1/articles/:id
def update
@article.update(article_attributes)
# ...
end
# ...
private
def set_article
@article = Article.find(params[:id])
end
def article_attributes
params.require(:data)
.require(:attributes)
.permit(:title, :description)
end
end
您应该在这里注意到的第一件事是,我们甚至根本没有使用JSON数据中的
params[:data][:id]
键,因为ID可从请求url(params[:id]
)获得。如果遵循RESTful模式,则您永远不需要使用params[:data][:id]
参数。在
article_attributes
中,我们使用嵌套的require调用,因为我们希望Rails引发ActionController::ParameterMissing
错误,除非提供的JSON数据证实了JSON API规范。 Vanilla Rails的默认设置是使用400 Bad Request响应进行救援-如果为JSONAPI正确设置了RailsAPI,它将返回422和一个JSON错误对象。
关于ruby-on-rails - 强大的参数JSON API rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31594567/