2010-10-21 45 views
6

在Rails 2.3,我總是用Rails的JSON注入

render :json => { :success => true, :data => @foobar} 

以JSON數據發送到我的前端。在Rails 3中,我正在使用

respond_to :json 
... 
respond_with @foobar 

但是我錯過了:我需要JSON結構內的'success'值。在Rails 3中將這些數據注入JSON響應的正確方法是什麼?


嗯,試過這種過,但我得到以下錯誤的結果:

SyntaxError (app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting '}' 
respond_with { :success => true, :data => @property } 
         ^
/app/controllers/properties_controller.rb:13: Can't assign to true 
respond_with { :success => true, :data => @property } 
           ^
app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.' 
respond_with { :success => true, :data => @property } 

回答

1

您不能使用對象一樣值。你剛纔裏面添加一些鍵/值與覆蓋serializable_hash方法

但是你可以生成你的散列respond_with

respond_with { :success => true, :data => @foobar} 
+0

Hmhm,也試過這個,但是我得到如下錯誤結果: – ctp 2010-10-21 08:15:31

4

當事情不適合默認情況下,你需要回到以前的定製方式。 respond_with接受一個塊。

respond_with @foobar do |format| 
    format.json { render :json => { :success => true, :data => @foobar} } 
end