2012-07-20 124 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 

有在整個系統中過多的注意事項派下來一個請求 - 唯一可行的辦法是隻發送必要的註釋(即屬於用戶正試圖查看的用戶或類別的註釋)。

我用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 

我們包括側向載荷數據在這裏,但你可以避開它,在ApplicationSerializerinclude參數設置爲false


的用戶,類別&音符會收到&通過燼數據緩存爲他們來了,並在需要時遺失物品將被要求。

+0

Will Ember Data會根據關聯自動請求使用相應的URL(/users/:user_id/notes.json或/categories/:category_id/notes.json)嗎? – user1539664 2012-07-20 05:55:39

+0

不,它會使用'/ notes',但是你的控制器將確保從(類別|用戶)開始的連接,遍歷關係,所以數據集將被限制爲只有有用的實例。 – 2012-07-20 06:03:56

+0

因此,無法從類別和用戶對象訪問註釋嗎? – 2012-08-17 13:53:30