【问题标题】:How to render a jsonapi-resources response in an custom controller action?如何在自定义控制器操作中呈现 jsonapi-resources 响应?
【发布时间】:2017-11-06 07:43:29
【问题描述】:

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

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

如何使用 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

【问题讨论】:

    标签: ruby-on-rails json jsonapi-resources


    【解决方案1】:

    你可以这样做:

    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
    

    这样您将获得符合 Jsonapi 标准的 json 响应

    【讨论】:

      【解决方案2】:
      渲染json:JSON.pretty_generate(JSON.parse @transaction)

      【讨论】:

        【解决方案3】:
        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 }
        

        【讨论】:

        • 这会呈现 JSON 响应,但它只是纯 JSON。它不符合 JSON API 标准。 jsonapi-resources gem 自动生成丰富的 JSON API 响应(带有链接、属性和关系)。
        • 对不起,我误解了这个问题,我不知道这个宝石
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-03
        • 1970-01-01
        • 2015-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多