Ruby on rails RoR:内置响应对象中的序列化数据
我正在构建一个Rails API,我有一个控制器方法,它用一个自定义对象进行响应:Ruby on rails RoR:内置响应对象中的序列化数据,ruby-on-rails,json,serialization,activerecord,controller,Ruby On Rails,Json,Serialization,Activerecord,Controller,我正在构建一个Rails API,我有一个控制器方法,它用一个自定义对象进行响应: class V1::AppInitController < ApplicationController def init json_response({ user: UserSerializer.new(current_user, {}).as_json, categories: ActiveModel::Serializer::CollectionSerializer.
class V1::AppInitController < ApplicationController
def init
json_response({
user: UserSerializer.new(current_user, {}).as_json,
categories: ActiveModel::Serializer::CollectionSerializer.new(Category.all, each_serializer: CategorySerializer).as_json,
last_seen_products: current_user.last_seen_products
})
end
end
classv1::AppInitController
由于我在这里构建一个自定义对象,如果我想应用序列化程序,我必须手动调用它们。
是否可以配置我的控制器,以便自动应用序列化程序
我最终想要的是能够以这种方式编写我的方法,并自动序列化:
class V1::AppInitController < ApplicationController
def init
json_response({
user: current_user,
categories: Category.all,
last_seen_products: current_user.last_seen_products
})
end
end
classv1::AppInitController
按如下所示修改您的init方法并尝试
class V1::AppInitController < ApplicationController
def init
json_response({
user: UserSerializer(current_user),
categories: CategorySerializer(Category.all),
last_seen_products: current_user.last_seen_products
})
end
end
classv1::AppInitController
我希望它对您有用。修改您的init方法,如下所示,然后再试一次
class V1::AppInitController < ApplicationController
def init
json_response({
user: UserSerializer(current_user),
categories: CategorySerializer(Category.all),
last_seen_products: current_user.last_seen_products
})
end
end
classv1::AppInitController
我希望这对你有用。谢谢你的回答。我的工作原理与此类似(除了类别数组,我使用的是ActiveModel::Serializer::CollectionSerializer),但是我尝试在使用
render:json
时应用序列化程序,而不必显式地在AMS中调用它们,并且如果您传递某个ApplicationRecord对象,默认情况下它将查找该对象的序列化程序。但是在您的例子中,您试图在render:json
中传递散列,因此它不会将散列转换为序列化程序。应用程序如何知道在何处使用序列化程序记录以及何时使用实际记录的其他方法谢谢您的回答。我的工作原理与此类似(除了类别数组,我使用的是ActiveModel::Serializer::CollectionSerializer),但是我尝试在使用render:json
时应用序列化程序,而不必显式地在AMS中调用它们,并且如果您传递某个ApplicationRecord对象,默认情况下它将查找该对象的序列化程序。但是在您的例子中,您试图在render:json
中传递散列,因此它不会将散列转换为序列化程序。另一方面,应用程序如何知道在哪里使用序列化程序记录以及何时使用实际记录我认为这是不可能的。但是,您可以创建一个新的序列化程序,将对象作为实例_选项传递,并在此序列化程序中调用各个序列化程序。所以,从控制器来看,您只使用这个新的序列化程序。我认为这是不可能的。但是,您可以创建一个新的序列化程序,将对象作为实例_选项传递,并在此序列化程序中调用各个序列化程序。因此,在控制器中,您只使用这个新的序列化程序。