2013-10-19 46 views
2

我在與模型Ember.js的問候與寧靜的服務器檢索數據(通過使用Sails.js的MongoDB服務)Ember.js REST風格的模型關係

我的路由器設置如下問題:

App.Router.map(function() { 
    this.route("dashboard"); 
    this.resource('exams', {path: "/exams"}, function() { 
     this.resource('exam', {path: ":exam_id"}, function(){ 
      this.resource('questions', function() { 
       this.route("new"); 
      }) 
     }) 
     this.route("view", {path: "/:exam_id" }); // for viewing exam details 
    }); 
}); 

基本上我得到可用的檢查清單,並能要麼它修改一些細節每一個,點擊看問題關聯列表。

我與考試資源沒有問題,這與寧靜的適配器訪問像這樣:

http://localhost:1337/api/v1/exams 

這將產生:

{ 
    exams: [ 
     { 
     user_id: "52444c03268a31ea0b000001", 
     title: "Introduction test", 
     private: false, 
     active: false, 
     showResults: false, 
     random: false, 
     _id: "52471342445565e74600000a" 
     }, 
     ... 
    ] 
} 

問題的資源並沒有嵌入並存儲在一個單獨的集合在MongoDB中並單獨訪問:

http://localhost:1337/api/v1/questions 

結果爲:

{ 
    questions: [ 
     { 
     _id: "52483f404617e6c728c4ed93", 
     title: "What's the capital of Moscow?", 
     exam_id: "52471342445565e74600000a" 
     }, 
     { 
     _id: "52483f6e4617e6c728c4ed94", 
     title: "What's the capital of Switzerland?", 
     exam_id: "52471342445565e74600120a" 
     } 
    ] 
} 

但是,問題應該總是與考試有關。據我所知,你不能在Ember.js中嵌套休息路線。我的理想休息路線是:

http://localhost:1337/api/v1/exams/52471342445565e74600000a/questions 

,以獲得特定的考試所有的問題,但我不知道這是否可以做到的。至少我從來沒有經理讓它工作。

所以要不斷保持它的簡單,我決定以REST風格查詢與exam_id問題只得到的特別考試相關問題清單:

http://localhost:1337/api/v1/questions/52471342445565e74600000a //<-- exam_id 

這回我需要的結果......僅此是不被Ember.js允許,因爲它認爲我得到一個單獨的問題w /特定的ID。我也試着考慮推exam_id來質疑寧靜的路線w/URL參數(../?exam_id=52471342445565e74600000a),但似乎queryParams不是Ember.js的一部分。我在Github上看到,至少在v 1.2之前不是。

所以我的問題是:如何通過證明外鍵來關聯和查詢這兩個模型? 我真的不想將所有東西都嵌入到一件事中。或者有更好的方式來管理模型之間的關係?

但有一點需要注意:我需要能夠正確地查詢服務器以檢索所需的記錄,而不是對整個預取數據進行排序。這是因爲不同的考試屬於不同的用戶,不同考試的問題不能被其他人看到(查詢)。

我有點新Ember.js所以任何建議(或更好的現實世界的例子)讚賞。

+0

您使用的餘燼數據? – Kingpin2k

回答

1

如果你使用Ember Data,那麼這個很簡單。

查詢字符串部分很簡單:

this.get('store').find('question', {exam_id: 123213});

會產生得到這樣的「/ API /問題?exam_id = 123213'

的關係部分是真棒,超級容易以及:

App.BlogPost = DS.Model.extend({ 
    comments: DS.hasMany("comment") 
}); 

App.Comment = DS.Model.extend({ 
    post: DS.belongsTo("blogPost") 
}); 
+0

酷!謝謝!有效 – kernelpanic