1

我正在使用序列化程序来格式化我的 rails-api 投影仪的 json 响应。我正在使用关注来格式化最终回复。我的代码片段如下

entry_controller.rb

class EntriesController < ApplicationController
  include Response

  def index
    @entries = @current_user.entries
    json_response(@entries)
  end
end

关注/response.rb

module Response
  def json_response(response, error = nil, message = 'Success', code = 200)
    render json: {
        code: code,
        message: message,
        error: error,
        response: response
    }
  end
end

application_serializer.rb

class ApplicationSerializer < ActiveModel::Serializer
end

entry_serializer.rb

class EntrySerializer < ApplicationSerializer
  attributes :title, :content, :is_encrypted, :entry_date
end

entry#index中,如果我使用json_response(@entries)我对请求的最终响应没有格式化,并且每个条目都与数据库中的一样。相反,如果我使用render json: @entries. 我按照序列化程序获得。我想将关注方法json_response(@entries)与序列化程序一起使用。有人可以建议一种在关注方法中以通用方式使用序列化程序的方法,因为多个控制器使用相同的关注方法。提前致谢。

4

2 回答 2

0

与序列化程序参数相关的内容是您想要自定义响应的内容。

class EntriesController < ApplicationController
      include Response

      def index
        @entries = @current_user.entries
        render json: @entries, serializer_params: { error: nil, message: "Success", code: 200}
      end
    end

class EntrySerializer < ApplicationSerializer
  attributes :title, :content, :is_encrypted, :entry_date
  params :error, :message, :code

  def attributes
    super.merge(:error, :message, :code)
  end

end
于 2017-11-11T15:44:17.047 回答
0

我不确定我是否完全理解您的问题,但是如果给定哈希值,我不相信递归render :json调用,就像在这种情况下一样。to_json所以你可能会在你的关注中寻找这样的东西:

  module Response
    def json_response(response, error = nil, message = 'Success', code = 200)
      render json: {
        code: code,
        message: message,
        error: error,
        response: response.to_json
      }
    end
  end
于 2017-11-11T19:14:38.247 回答