2012-07-20 5 views
5

のは、私は(この私の実際のプロジェクトからのビット簡体字)、次のレイアウトでのRailsアプリを持っているとしましょう:エンバーデータネストされたリソースのURL

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

User 
    has many Notes 

Category 
    has many Notes 

Note 
    belongs to User 
    belongs to Category 

ノートのいずれかで得ることができます

ではなく:

/notes.json 

1つの要求にダウン送信するために、システム全体にわたる非常に多くの注意事項があります - 唯一の実行可能な方法があるには、必要なノートのみを送信します(つまり、ユーザーが表示しようとしているユーザーまたはカテゴリのいずれかに属するノート)。

Ember Dataでこれを実装するにはどうすればよいですか?

答えて

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 

ここではサイドロードデータが含まれていますが、ApplicationSerializerfalseincludeパラメータを設定、それを避けることができます。


ユーザー、カテゴリ&ノートは&受け、彼らが来るようエンバー・データによってキャッシュされ、必要に応じて不足している項目が要求されますされます。

+0

Ember Dataは関連付けだけに基づいて適切なURL(/users/:user_id/notes.jsonまたは/categories/:category_id/notes.json)を使用して自動的にリクエストしますか? – user1539664

+0

いいえ、 '/ notes'を使用しますが、あなたのコントローラは(categories | users)からの結合、トラバース関係を確実にするので、データセットは有用なインスタンスだけに制限されます。 –

+0

CategoryオブジェクトとUserオブジェクトの両方のメモにアクセスする方法はありませんか? –

関連する問題