use*_*664 5 ember.js ember-data
假设我有一个带有以下布局的Rails应用程序(从我的实际项目中简化了一下):
User
has many Notes
Category
has many Notes
Note
belongs to User
belongs to Category
Run Code Online (Sandbox Code Playgroud)
注释可以在以下位置获得:
/users/:user_id/notes.json
/categories/:category_id/notes.json
Run Code Online (Sandbox Code Playgroud)
但不是:
/notes.json
Run Code Online (Sandbox Code Playgroud)
在整个系统中有太多的Notes要在一个请求中向下发送 - 唯一可行的方法是仅发送必要的Notes(即,属于用户试图查看的用户或类别的Notes).
用Ember Data实现这个的最佳方法是什么?
我会说简单:
灰烬模特
App.User = DS.Model.extend({
name: DS.attr('string'),
notes: DS.hasMany('App.Note')
});
App.Category = DS.Model.extend({
name: DS.attr('string'),
notes: DS.hasMany('App.Note')
});
App.Note = DS.Model.extend({
text: DS.attr('string'),
user: DS.belongsTo('App.User'),
category: DS.belongsTo('App.Category'),
});
Run Code Online (Sandbox Code Playgroud)
Rails控制器
class UsersController < ApplicationController
def index
render json: current_user.users.all, status: :ok
end
def show
render json: current_user.users.find(params[:id]), status: :ok
end
end
class CategoriesController < ApplicationController
def index
render json: current_user.categories.all, status: :ok
end
def show
render json: current_user.categories.find(params[:id]), status: :ok
end
end
class NotesController < ApplicationController
def index
render json: current_user.categories.notes.all, status: :ok
# or
#render json: current_user.users.notes.all, status: :ok
end
def show
render json: current_user.categories.notes.find(params[:id]), status: :ok
# or
#render json: current_user.users.notes.find(params[:id]), status: :ok
end
end
Run Code Online (Sandbox Code Playgroud)
注意:这些控制器是简化版本(索引可以根据请求的ID进行过滤,......).您可以查看如何使用ember数据获取parentRecord id以供进一步讨论.
主动模型序列化器
class ApplicationSerializer < ActiveModel::Serializer
embed :ids, include: true
end
class UserSerializer < ApplicationSerializer
attributes :id, :name
has_many :notes
end
class CategorySerializer < ApplicationSerializer
attributes :id, :name
has_many :notes
end
class NoteSerializer < ApplicationSerializer
attributes :id, :text, :user_id, :category_id
end
Run Code Online (Sandbox Code Playgroud)
我们包括侧向载荷数据在这里,但你可以避开它,设定include参数false在ApplicationSerializer.
用户,类别和备注将在ember-data接收和缓存时显示,并且将根据需要请求缺少的项目.
| 归档时间: |
|
| 查看次数: |
2229 次 |
| 最近记录: |