如何在自定义控制器操作中呈现jsonapi-resources响应?

我通过覆盖JSONAPI :: ResourceController控制器中的create动作实现了我自己的对象创建逻辑。

成功创建后,我想显示创建的对象表示。

如何使用jsonapi-resources gem渲染这个自动生成的JSON API响应?

调用super方法也会触发默认的资源创建逻辑,所以这对我来说不起作用。

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 

 渲染json:JSON.pretty_generate(JSON.parse @transaction) 
 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 

通过这种方式,您将获得符合Jjsonapi标准的json响应

Interesting Posts