简体   繁体   English

在关注栏内使用序列化器

[英]using serializer inside concern rails

I am using serializer to format json response of my rails-api projector. 我正在使用序列化器来格式化我的rails-api投影仪的json响应。 I am using a concern to format final response. 我使用某种格式来格式化最终答复。 My code snippets are as follows 我的代码段如下

entry_controller.rb entry_controller.rb

class EntriesController < ApplicationController
  include Response

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

concerns/response.rb 关注/响应.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 application_serializer.rb

class ApplicationSerializer < ActiveModel::Serializer
end

entry_serializer.rb entry_serializer.rb

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

In entries#index if i use json_response(@entries) my final response of request is not formatted and each entry is as in database. 如果我使用json_response(@entries),在entrys #index中 ,我对请求的最终响应未格式化,并且每个条目都与数据库中的一样。 instead if i use render json: @entries . 相反,如果我使用render json: @entries Im getting as per serializer. 我按序列化程序获取。 I want to use concern method json_response(@entries) along with serializers. 我想将关注方法json_response(@entries)与序列化程序一起使用。 Can someone suggest a way to use serializers in concern methods in a generic way as multiple controllers use same concern method. 有人可以建议一种在关注方法中使用序列化器的方法吗,因为多个控制器使用相同的关注方法。 Thanks in advance. 提前致谢。

Something related to serializer params is what you want to customise your response. 与序列化程序参数相关的是您要自定义响应的内容。

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

I'm not sure I fully understand your question, but I don't believe render :json calls to_json recursively if it is given a hash, like in this case. 我不确定我是否完全理解您的问题,但是我不相信render :json如果给定哈希值, to_json递归调用to_json ,在这种情况下。 So you may be looking for something like this in your concern: 因此,您可能正在关注这样的问题:

  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