2011-06-02 53 views
0

對於那些使用Rails作爲其Sproutcore客戶端的後端, 哪一種是將數據格式化爲json的最佳方式?從rails到sproutcore的json格式

從SproutCore的引導出現了這種方法:

def as_json(options = {}) 
    event_hash = { 
    "guid" => self.id, 
    "id" => self.id, 
    "designation" => self.designation, 
    "category" => self.category, 
    "scheduled_for" => self.scheduled_for, 
    "location" => self.location, 
    "groups" => self.groups, 
    "resources" => self.resources 
    } 

    event_hash 
end 

但失敗,發送一個「非法語句錯誤」。然後,我改變了這個另一種方法:

def as_json(options = {}) 
    # event_hash = options.merge(:include => [:groups, :resources], :methods => :guid) 
    event_hash = options.merge(:methods => :guid) 
    super(event_hash) 
end 

這似乎只要格式來說是工作,雖然我也懷疑到引起關於商店的dataHash表示了一些麻煩。無論如何,任何人都有與第一版as_json類似的問題?如果不是,我做錯了什麼?

感謝所有幫助

回答

1

在您需要調用超第一種方法:

def as_json(options = {}) 
    event_hash = { 
    "guid" => self.id, 
    "id" => self.id, 
    "designation" => self.designation, 
    "category" => self.category, 
    "scheduled_for" => self.scheduled_for, 
    "location" => self.location, 
    "groups" => self.groups, 
    "resources" => self.resources 
    } 

    super(event_hash) 
end 

然而,你應該得到的選項PARAM和過程apropiately做到這一點。

+0

'超()'電話是兩個最初的海報名單之間的最大區別,所以我認爲這是正確的軌道。 – pjmorse 2011-06-02 14:58:44

+0

可否請您詳細說明處理選項參數?我將這個調用添加到super,並且它在沒有引發異常的情況下工作。但是,我只得到一個記錄發送到sproutcore。有什麼我失蹤? – joque 2011-06-03 13:01:10

+0

您應該使用您用作參數的'options'並將其與默認選項合併爲例。 – decay 2011-06-10 07:38:43