gpt4 book ai didi

ruby-on-rails - 强大的参数JSON API rails

转载 作者:行者123 更新时间:2023-12-03 21:44:36 29 4
gpt4 key购买 nike

我正在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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com