Ember数据:未捕获的TypeError:无法调用未定义的方法'modelFor'

时间:2014-03-02 21:31:33

标签: ember.js ember-data

我正在尝试使用ember数据定义我的模型,但出于某种原因,只要我添加一些 hasManybelongsTo关系,我就会收到错误'Uncaught TypeError:无法调用方法'modelFor'未定义的'

我做错了什么?

App.User = DS.Model.extend({
  username: DS.attr('string'),
  facebook_id: DS.attr('string'),
  staff: DS.attr('boolean', {defaultValue: false}),
  createdAt: DS.attr('date'),
  posts: DS.hasMany('post', {async: true}),
  comments: DS.hasMany('comment', {async: true)
})

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  image: DS.attr('string'),
  track: DS.attr('string'),
  createdAt: DS.attr('date'),
  user: DS.belongsTo('user'),
  comments: DS.hasMany('comment', {async: true})
})

App.Comment = DS.Model.extend({
  user: DS.belongsTo('user'),
  post: DS.belongsTo('post'),
  track: DS.attr('string'),
  createdAt: DS.attr('date')
})

2 个答案:

答案 0 :(得分:1)

通过在关系中指定应用名称来解决此问题,例如:而不是hasMany('comment')我使用hasMany('App.Comment')。不确定发生了什么,因为前者是文档中显示的内容。

App.User = DS.Model.extend({
  username: DS.attr('string'),
  facebook_id: DS.attr('string'),
  staff: DS.attr('boolean', {defaultValue: false}),
  createdAt: DS.attr('date'),
  posts: DS.hasMany('App.Post', {async: true}),
  comments: DS.hasMany('App.Comment', {async: true)
})

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  image: DS.attr('string'),
  track: DS.attr('string'),
  createdAt: DS.attr('date'),
  user: DS.belongsTo('App.User'),
  comments: DS.hasMany('App.Comment', {async: true})
})

App.Comment = DS.Model.extend({
  user: DS.belongsTo('App.User'),
  post: DS.belongsTo('App.Post'),
  track: DS.attr('string'),
  createdAt: DS.attr('date')
})

答案 1 :(得分:0)

另请注意,引用不存在的模型时可能会出现此错误,例如:

App.ItServiceUser = DS.Model.extend({
    companyService: DS.belongsTo('App.CompanyITService'),
    employee: DS.belongsTo('App.AllEmployee'),
    employeeID: attr('string'),
    isLeadAdmin: attr('string'),
    isAdmin: attr('boolean'),
    isEditing: attr('boolean'),
    username: attr('string'),
    firstName: attr('string'),
    lastName: attr('string'),
    userChoiceSet: attr('string')
})

从控制台中删除此代码:

> user = App.ItServiceUser.find(2216)
g {id: "2216", store: g, _reference: Object, stateManager: (...), _changesToSync: Object…}
> user.set("lastName", "Anthony")
g {id: "2216", store: g, _reference: Object, stateManager: (...), _changesToSync: Object…}
> user.save()
q {_promiseCallbacks: Object, constructor: function, then: function, on: function, off: function…}
Uncaught TypeError: Cannot read property 'toString' of undefined ember-data.js:2540

删除了引用不存在的模型的行,我很好:

companyService: DS.belongsTo('App.CompanyITService'),