5

次のレイアウトの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

システム全体で 1 回の要求で送信するにはメモが多すぎます。実行可能な唯一の方法は、必要なメモ (つまり、ユーザーが表示しようとしているユーザーまたはカテゴリのいずれかに属するメモ) のみを送信することです。

Ember Data でこれを実装する最善の方法は何でしょうか?

4

1 に答える 1

5

私は簡単に言うでしょう:

エンバーモデル

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パラメーターをfalseinに設定することで回避できますApplicationSerializer


ユーザー、カテゴリ、およびメモは、受信時に ember-data によって受信およびキャッシュされ、不足しているアイテムは必要に応じて要求されます。

于 2012-07-20T05:52:31.963 に答える