私はシンプル言う:
エンバーモデル
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
ここではサイドロードデータが含まれていますが、ApplicationSerializer
にfalse
にinclude
パラメータを設定、それを避けることができます。
ユーザー、カテゴリ&ノートは&受け、彼らが来るようエンバー・データによってキャッシュされ、必要に応じて不足している項目が要求されますされます。
Ember Dataは関連付けだけに基づいて適切なURL(/users/:user_id/notes.jsonまたは/categories/:category_id/notes.json)を使用して自動的にリクエストしますか? – user1539664
いいえ、 '/ notes'を使用しますが、あなたのコントローラは(categories | users)からの結合、トラバース関係を確実にするので、データセットは有用なインスタンスだけに制限されます。 –
CategoryオブジェクトとUserオブジェクトの両方のメモにアクセスする方法はありませんか? –