在Emberjs中获取一个sigleton嵌套的singleton资源

时间:2016-02-04 13:35:53

标签: ruby-on-rails api ember.js ember-data

我正在尝试获取具有以下路由的单例资源:/api/users/:user_id/profile。用户模型对配置文件一无所知。模型在Rails中定义如下:

class UserProfile < ActiveRecord::Base
  belongs_to :user
end

如何定义EmberJS模型和路线,以便在我转到/users/1/profile时获取用户的个人资料?我一直试图找出如何在EmberJS中定义单例资源但找不到合适的东西。

2 个答案:

答案 0 :(得分:1)

我认为您需要一个适配器,例如:

<强>适配器/用户profile.js

import ActiveModelAdapter from 'active-model-adapter';

export default ActiveModelAdapter.extend({
  namespace: 'api/users',
  pathForType() {
    return 'user_profile';
  },

  urlForFindRecord(id, modelName) {
    return this.urlForFindAll(modelName);
  },

  urlForUpdateRecord(id, modelName) {
    return this.urlForFindAll(modelName);
  }
});

答案 1 :(得分:1)

“用户对个人资料一无所知”,您是否认为/api/users/:user_id的API响应中不包含对/api/users/:user_id/profile的任何引用?如果是这样,你总是可以告诉 Ember。

假设JSON-API:

// serializer:user
normalize(type, hash, prop) {
  const result = this._super(type, hash ,prop);
  const userId = result.data.id;
  result.relationships.userProfile = {
    links: { related: `/api/users/${userId}/profile` }
  };
  return result;
}

或者,如果您使用的是较旧的Ember-Data:

// serializer:user
normalizeRelationships(type, hash) {
  hash.links = hash.links || {};
  hash.links.userProfile = `/api/users/${userId}/profile`;
  return this._super(type, hash);
}

然后,model:user可以有userProfile关系:

// model:user
userProfile: DS.belongsTo('userProfile', { async: true })
相关问题