Rails JSON注入

ctp*_*ctp 6 json ruby-on-rails

在Rails 2.3中我总是使用

render :json => { :success => true, :data => @foobar}
Run Code Online (Sandbox Code Playgroud)

将JSON数据发送到我的前端.在Rails 3我正在使用

respond_to :json
...
respond_with @foobar
Run Code Online (Sandbox Code Playgroud)

但我缺少的是:我需要JSON结构中的"成功"值.在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 }
Run Code Online (Sandbox Code Playgroud)

shi*_*ara 1

您不能使用类似对象的值。serializable_hash您只需使用覆盖方法在其中添加一些键/值

但是你可以在respond_with中生成你的哈希值

respond_with { :success => true, :data => @foobar}
Run Code Online (Sandbox Code Playgroud)