我会说简单:
余烬模型
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'),
});
导轨控制器
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
请注意:这些控制器是简化版本(索引可能会根据请求的 id 进行过滤,...)。您可以查看How to get parentRecord id with ember data以进行进一步讨论。
活动模型序列化器
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
include
我们在此处包含侧载数据,但您可以通过将参数设置为false
in来避免它ApplicationSerializer
。
ember-data 将接收并缓存用户、类别和注释,并根据需要请求丢失的项目。