我有一个应用程序,它有两个模型Image和Project。图像属于项目,项目有许多图像。
我之前设置过这样,以便图像存储在本地,一切正常,但由于Heroku不支持上传文件的本地存储,我设置了一个Amazon S3存储桶来处理图像存储。
我遇到的问题是,在我的项目页面上,应该显示项目的第一张图片,但它不会加载或显示任何错误。
#app/assets/javascripts/models/project.js
App.Project = DS.Model.extend({
name: DS.attr('string'),
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', {async: true}),
projectDuration: function() {
return this.get('start_date') + ' to ' + this.get('end_date')
}.property('start_date', 'end_date'),
firstImage: function() {
var projectImages = this.get('images');
var projectImage = projectImages.get('firstObject');
return projectImage;
}.property('images')
});
#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/store.js
DS.RESTAdapter.reopen({
namespace: 'api/v1'
})
App.Store = DS.Store.extend({});
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({});
#app/assets/javascripts/templates/projects.js.emblem
section
.container
.row
.col-xs-12.col-sm-10.col-sm-offset-1.col-md-8.col-md-offset-2
.row
each project in controller
link-to 'project' project
.col-xs-12
img.transition src=project.firstImage._project_image
h1.text-center.text-uppercase = project.client
p.subtext.text-center = project.tags
#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, :name, :client, :tags, :description, :start_date, :end_date
has_many :images, embed: :ids, include: true
end
使用本地存储时,我没有在项目模型中包含{async: true}
,但这会产生错误:
You looked up the 'images' relationship on '<App.Project:ember356:9>' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (
DS.hasMany({async:true}))
然后我指定{async: true}
,我的图片不会加载到项目模板上。
但他们仍然在我的项目模板中加载。
答案 0 :(得分:0)
我刚刚解决了这个问题!
事实证明,你需要明确地将异步关系声明为true或false - 不要完全删除该选项。
我最终得到了:
#app/assets/javascripts/models/project.js
App.Project = DS.Model.extend({
name: DS.attr('string'),
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', {async: false}),
projectDuration: function() {
return this.get('start_date') + ' to ' + this.get('end_date')
}.property('start_date', 'end_date'),
firstImage: function() {
var projectImages = this.get('images');
var projectImage = projectImages.get('firstObject');
return projectImage;
}.property('images')
});