使用ActiveModel :: Serializers来包含两个父json数组 [英] Use ActiveModel::Serializers to include two parent json arrays
问题描述
我正在尝试发送我的前端应用程序json,如下所示:
I'm trying to send my front-end application json that looks like this:
{
facilities: [
{id: 5, name: 'happy days ranch', location: { address: '1424 Pastoral Lane', zipcode: '25245'}, instructor_ids: [2, 4, 9]}
],
instructors: [
{id: 4, name: 'Johnny Pheonix', skill: '8', picture: 'aws_url', facility_ids: [5, 8, 12}
]
}
我尝试过的东西
Things I have tried
render :json => @facilities
序列化程序发现了这一点。好极了!但是这不包括任何教练
The serializer discovers this. Yay! But this does not include any instructors
render :json => {facilities: @facilities, instructors: @instructors}
这给了我一个讲师数组和一个设施数组,但是没有使用activeModel :: Serializers。
This gives me an instructors array and a facilities array, but activeModel::Serializers is not used.
render :json => [@facilities, @instructors]
起初我很兴奋这个,因为它给了我两个数组,并使用ActiveModel :: Serializers。但是,这是JSON的样子:
At first I was excited about this one, because it gave me two arrays, and it used ActiveModel::Serializers. However, this is what the JSON looked like:
{facilities: [
{facilities: [
#my facilities data
]},
{facilities: [
#my instructor data
]}
]}
我正在尝试甚至允许ActiveModel :: Serializers?如果是这样,怎么样?
提前感谢!
Is what I'm trying to do even allowed by ActiveModel::Serializers? If so, how?
Thanks much in advance!
推荐答案
我通过创建一个名为Search的类来解决它,其中包含ActiveModel的各个方面
I solved it by creating a class called Search that incorporates aspects of ActiveModel
class Search
include ActiveModel::Serialization
include ActiveModel::SerializerSupport
attr_accessor :facilities, :instructors
def initialize(facilities, instructors)
@facilities, @instructors = facilities, instructors
end
end
然后我创建了一个搜索控制器(没有什么有趣的)和一个搜索序列化程序。
Then I created a Searches controller (nothing interesting there) and a Search serializer.
class SearchSerializer < ActiveModel::Serializer
has_many :instructors, embed: :objects
has_many :facilities, embed: :objects
end
这创建了我想要的json,虽然现在它被包装在搜索哈希中:
This creates my desired json, although now it is wrapped in a search hash:
{search: {
#the stuff I wanted
}}
这篇关于使用ActiveModel :: Serializers来包含两个父json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!