繁体   English   中英

在关注栏内使用序列化器

[英]using serializer inside concern rails

我正在使用序列化器来格式化我的rails-api投影仪的json响应。 我使用某种格式来格式化最终答复。 我的代码段如下

entry_controller.rb

class EntriesController < ApplicationController
  include Response

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

关注/响应.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

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

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

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

我不确定我是否完全理解您的问题,但是我不相信render :json如果给定哈希值, to_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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM