Ruby on rails 如何在自定义控制器操作中呈现jsonapi资源响应?
通过重写JSONAPI::ResourceController控制器中的创建操作,我实现了自己的对象创建逻辑 成功创建后,我希望渲染创建的对象表示 如何使用jsonapi资源gem呈现自动生成的JSON API响应? 调用super方法也会触发默认的资源创建逻辑,所以这对我来说是行不通的Ruby on rails 如何在自定义控制器操作中呈现jsonapi资源响应?,ruby-on-rails,json,jsonapi-resources,Ruby On Rails,Json,Jsonapi Resources,通过重写JSONAPI::ResourceController控制器中的创建操作,我实现了自己的对象创建逻辑 成功创建后,我希望渲染创建的对象表示 如何使用jsonapi资源gem呈现自动生成的JSON API响应? 调用super方法也会触发默认的资源创建逻辑,所以这对我来说是行不通的 class Api::V1::TransactionsController < JSONAPI::ResourceController def create @transaction = Tr
class Api::V1::TransactionsController < JSONAPI::ResourceController
def create
@transaction = Transaction.create_from_api_request(request.headers, params)
# render automatic generated JSON API response (object representation)
end
end
class Api::V1::TransactionController
render json:json.pretty_generate(json.parse@transaction)您可以这样做:
class UsersController < JSONAPI::ResourceController
def create
user = create_user_from(request_params)
render json: serialize_user(user)
end
def serialize_user(user)
JSONAPI::ResourceSerializer
.new(UserResource)
.serialize_to_hash(UserResource.new(user, nil))
end
end
class UsersController
通过这种方式,您将获得一个符合Jsonapi标准的json响应这确实提供了一个json响应,但它只是简单的json。它不符合JSON API标准。jsonapi资源gem会自动生成丰富的jsonapi响应(带有链接、属性和关系)
def render_json
result =
begin
block_given? ? { success: true, data: yield } : { success: true }
rescue => e
json_error_response(e)
end
render json: result.to_json
end
def json_error_response(e)
Rails.logger.error(e.message)
response = { success: false, errors: e.message }
render json: response.to_json
end
render_json { values }
class UsersController < JSONAPI::ResourceController
def create
user = create_user_from(request_params)
render json: serialize_user(user)
end
def serialize_user(user)
JSONAPI::ResourceSerializer
.new(UserResource)
.serialize_to_hash(UserResource.new(user, nil))
end
end