我正在使用序列化程序来格式化我的 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)
与序列化程序一起使用。有人可以建议一种在关注方法中以通用方式使用序列化程序的方法,因为多个控制器使用相同的关注方法。提前致谢。