2011-11-30 101 views
10

我已經在軌道定義了以下路線:骨幹和Rails嵌套路線

resources :accounts do 
    resources :transactions 
end 

這導致像URL:

/accounts/123/transactions/1 

有一種簡單的方法來此映射到骨幹模型集合向上?

回答

21

變成主幹很容易通過在mo中嵌套集合來支持del如下:

var Account = Backbone.Model.extend({ 

    initialize: function() { 
    this.transactions = new TransactionsCollection; 
    this.transactions.url = '/account/' + this.id + '/transactions'; 
    this.transactions.bind("reset", this.updateCounts); 
    }, 
}); 

這實現了我想要的。

你可以閱讀更多關於它在這裏:http://documentcloud.github.com/backbone/#FAQ-nested

+2

這適用於通過獲取調用從後端加載的現有模型。但是我剛剛創建的模型呢?當調用initialize方法時,在後端創建記錄的ajax調用還沒有完成,'this.id'字段是'undefined'。有關如何應對這個問題的任何想法? – Ernesto

+0

處理剛剛創建的模型的url生成的一種方法是使url成爲函數而不是字符串。因此,上面的行可以改爲:'this.transactions.url = function(){return'/ account /'+ this.id +'/ transactions'};'' – stereoscott

1

只要定義模型或網址(如果你使用一個)您的收藏像這樣:

var MyModel = Backbone.Model.extend({ 
    url: 'accounts/123/transactions' 
}); 

或動態:

mymodel.url = 'accounts/' + accountId + '/transactions'; 

這些模型或集合,是全系車型按此方式配置現在將相應地生成它的後端URL。

詳細信息:

型號: http://documentcloud.github.com/backbone/#Model-url

收藏: http://documentcloud.github.com/backbone/#Collection-url

+0

第一可能不會在它的工作將意味着所有的交易將屬於一個帳戶,這是情況並非如此。例如,如果可以將url定義爲「accounts /:account_id/transactions」,那就太好了。 我會調查第二個選項。 –

+1

也可以重寫模型和集合的url()方法。更復雜的網址構建機制可以在那裏實現。 – ProTom

4

它可能不是一個簡單的方法,但我認爲最好的方法是使用URL並將其設置爲一個功能像這樣:

var Transaction = Backbone.Model.extend({ 
    url: function(){ 
     var url = 'accounts/"+this.account_id+"/transactions'; 
     if (this.id !== undefined){ 
      url += "/"+this.id 
     } 
     return url; 
    } 
}); 

或者可能在coffeescript(因爲它是倒退一個+軌):

class Transaction extends Backbone.Model 
    url: -> 
     url = "accounts/#{@account_id}/transactions" 
     url += "/#{@id}" if @id != undefined 
     url 

哦,你更喜歡這樣(能做到這一點肯定有更深層次的嵌套它的更好):

var url = ["accounts", this.account_id, "transactions"] 
if (this.id !== undefined) url.push(this.id) 
return url.join("/") 


據我所知現在有骨幹URL工具,這對我來說並不足夠痛苦,所以我會在其他一些庫中搜索一個:)

2

骨幹並不直接支持嵌套的URL的創建。您必須使用函數來動態計算嵌套對象的結果url。例如:

var Account = Backbone.Model.extend({ 

    initialize: function() { 
    this.transactions = new TransactionsCollection(); 
    var self = this; 
    this.transactions.url = function() {return self.url + self.id + '/transactions';}; 
    // etc 
    }, 
}); 

的更多信息:http://documentcloud.github.com/backbone/#FAQ-nested