Ember Data嵌套资源URL

时间:2012-07-20 04:04:57

标签: ember.js ember-data

假设我有一个带有以下布局的Rails应用程序(从我的实际项目中简化了一下):

User
    has many Notes

Category
    has many Notes

Note
    belongs to User
    belongs to Category

注释可以在以下地址获得:

/users/:user_id/notes.json
/categories/:category_id/notes.json

但不是:

/notes.json

整个系统中有太多的Notes要在一个请求中向下发送 - 唯一可行的方法是只发送必要的Notes(即属于用户试图查看的用户或类别的Notes)。 / p>

使用Ember Data实现此目的的最佳方式是什么?

1 个答案:

答案 0 :(得分:5)

我会说简单:

Ember模特

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'),
});

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

注意:这些控制器是简化版本(索引可能会根据请求的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中的ApplicationSerializer


用户,类别&amp;将收到笔记&amp;它们来自ember-data缓存,将根据需要请求丢失的项目。

相关问题