2012-07-20 2 views
5

의 내가 (이 내 실제 프로젝트에서 비트 간체) 다음과 같은 레이아웃 레일 응용 프로그램이 있다고 가정 해 봅시다 :엠버 데이터 중첩 된 자원 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 

전체 시스템에 걸쳐 너무 많은주의가 하나 개의 요청에 내려 보낼 수있는이 - 유일하게 가능한 방법이다 필요한 메모 (예 : 사용자가 보려는 사용자 또는 범주에 속하는 메모).

엠버 데이터로 이것을 구현하는 최선의 방법은 무엇입니까?

답변

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

레일 컨트롤러

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 

우리는 여기 SIDELOAD 데이터를 포함,하지만 당신은 ApplicationSerializerfalseinclude 매개 변수를 설정, 그것을 피할 수 있습니다.


사용자 범주 & 노트 &받은 그들이 와서 엠버 데이터 캐시, 필요에 따라 누락 된 항목이 요청 될 것입니다.

+0

Ember Data는 관련성을 기반으로 적절한 URL (/users/:user_id/notes.json 또는 /categories/:category_id/notes.json)을 사용하여 자동으로 요청합니까? – user1539664

+0

아니요,'/ notes'를 사용 합니다만, 컨트롤러는 (categories | users)부터 시작하여 조인, 트래버 싱 관계를 보장하므로 데이터 집합은 유용한 인스턴스로만 제한됩니다. –

+0

따라서 Category 및 User 객체의 노트에 액세스 할 수있는 방법이 없습니까? –

관련 문제