目前我的带有ember前端应用程序的rails API中的JSON格式不正确,我的图像模型如下所示。
这导致ember Chrome工具将我的Project_image的数据显示为“object Object”,将project_id显示为“null”,这在我的模板中不是很有用。
如何使用Active_Model_Serializer格式化JSON以正确输出数据。
当前的JSON示例:
{
"images":
[
{
"id":6,
"project_image":
{"project_image":
{"url":"/uploads/image/project_image/6/example_image.jpg"}
},
"project_id":8
}
]
}
当前image_serializer.rb
class ImageSerializer < ActiveModel::Serializer
attributes :id, :project_image, :project_id
end
任何帮助将不胜感激! :)
Ember Models
图像
App.Image = DS.Model.extend({
project_image: DS.attr('string'),
project_id: DS.attr('number'),
project: DS.belongsTo('project')
});
项目
App.Project = DS.Model.extend({
client: DS.attr('string'),
tags: DS.attr('string'),
description: DS.attr('string'),
start_date: DS.attr('string'),
end_date: DS.attr('string'),
images: DS.hasMany('image')
});
Rails模型
图像
class Image < ActiveRecord::Base
belongs_to :project
mount_uploader :project_image, ImageUploader
end
项目
class Project < ActiveRecord::Base
has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, allow_destroy: true
end
所有项目模型数据都正确加载,错误仅适用于图像模型。
答案 0 :(得分:1)
更新: 我认为这样的事情可以解决问题:
class ImageSerializer < ActiveModel::Serializer
attributes :id, :project_image_url, :project_id
def project_image_url
project.image_url
end
end
关键是将URL作为字符串发送。您也可以使用该名称,只需确保名称在Ember模型中匹配。
您使用的是哪个版本的active_model_serializers?我有类似的问题。 0.8.x按我the Readme修复了它。
答案 1 :(得分:0)
对于对解决方案感兴趣的任何人,我使用DavidKovsky创建自定义方法的想法,以确保以正确的格式传递JSON数据。
#app/serializers/image_serializer.rb
class ImageSerializer < ActiveModel::Serializer
attributes :id, :_project_image, :_project_id
def _project_image
object.project_image.to_s
end
def _project_id
object.project_id.to_i
end
end
#app/serializers/project_serializer.rb
class ProjectSerializer < ActiveModel::Serializer
attributes :id, :client, :tags, :description, :start_date, :end_date
has_many :images, embed: :ids, include: true
end
#app/assets/javascripts/models/image.js
App.Image = DS.Model.extend({
_project_image: DS.attr('string'),
_project_id: DS.attr('number'),
project: DS.belongsTo('project')
});
#app/assets/javascripts/models/project.js
App.Project = DS.Model.extend({
client: DS.attr('string'),
tags: DS.attr('string'),
description: DS.attr('string'),
start_date: DS.attr('string'),
end_date: DS.attr('string'),
images: DS.hasMany('image')
});
#app/assets/javascripts/store.js
DS.RESTAdapter.reopen({
namespace: 'api/v1'
})
App.Store = DS.Store.extend({});
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({});
#app/assets/javascripts/templates/project.js.emblem
each image in model.images
img src=image._project_image
#app/assets/javascripts/templates/project.js.hbs
{{ #each image in model.images }}
img src="{{ image._project_image }}"
{{ /each }}
在我的gemfile中我使用rails'4.2.0.beta4'和active_model_serializers'0.8.3'
我可以看到,如果你有很多属性可以转换成字符串,整数等,这种工作可能会变得很麻烦,但它至少在短期内起作用。
希望这有助于某人并再次感谢DavidKovsky的帮助。