我有一个对象(Institution),我希望使用JSON获得与此对象关联的2个数组(标记和附件)。
要清楚:对于1个机构,我有3个分数,每个分数我都有附件。
这是我的JSON
档案代码:
if @data['admin_institution']
json.extract! @data['admin_institution'], :id, :name, :phone, :address, :site, :created_at, :updated_at
if @data['admin_institution'].marks
json.marks @data['admin_institution'].marks
json.array!(@data['admin_institution'].marks) do | admin_mark|
json.attachment admin_mark.attachment
end
end
else
json.set! :response do
json.set! :error, 'Not Found!'
end
end
我想重现这样的事情:
{
id: 14,
name: "Ins3",
phone: "793215-2555",
address: "lreewrwklkr",
site: "lkerlke.com",
created_at: "2016-03-01T14:00:37.000-03:00",
updated_at: "2016-03-01T14:00:37.000-03:00",
- marks: [
- {
id: 17,
admin_attachment_id: 927,
admin_bookmark_id: 3,
admin_institution_id: 14,
created_at: "2016-03-01T14:00:37.000-03:00",
updated_at: "2016-03-01T14:00:37.000-03:00"
},
{
id: 18,
admin_attachment_id: 945,
admin_bookmark_id: 1,
admin_institution_id: 14,
created_at: "2016-03-01T14:00:37.000-03:00",
updated_at: "2016-03-01T14:00:37.000-03:00"
}
],
- attachment: {
id: 927,
name: "nature-16",
title: "Nature-16",
description: null,
mime_type: "image/jpeg",
url: "/uploads/nature-16.jpg",
created_at: "2016-02-29T09:21:09.000-03:00",
updated_at: "2016-02-29T09:21:09.000-03:00"
}
}
相反,我只获得了最后array
(附件)的值。提前谢谢。
更新
我在我的机构模型上使用through-association
然后我可以直接获得附件""通过标记,不做loop
标记。以下code
给了我几乎所有我想要的东西。
if @data['admin_institution']
json.extract! @data['admin_institution'], :id, :name, :phone, :address, :site, :created_at, :updated_at, :marks, :attachments
else
json.set! :response do
json.set! :error, 'Not Found!'
end
end
它返回了机构,标记和附件,但是没有嵌套。我希望机构内部的标记和标记内的附件。我怎样才能使它发挥作用?
答案 0 :(得分:0)
试试这个:
if @data['admin_institution']
...
if @data['admin_institution'].marks
json.marks @data['admin_institution'].marks do | admin_mark|
json.attachment admin_mark.attachment
end
end
else
...
end