gpt4 book ai didi

ruby-on-rails - Rails JSON 注入(inject)

转载 作者:行者123 更新时间:2023-12-04 06:28:16 25 4
gpt4 key购买 nike

在 Rails 2.3 中,我一直使用

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

将 JSON 数据发送到我的前端。在 Rails 3 我正在使用
respond_to :json
...
respond_with @foobar

但我缺少的是:我需要 JSON 结构中的“成功”值。在 Rails 3 中将此类数据注入(inject) 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 }

最佳答案

当事情不符合默认值时,您需要回到以前的自定义方式。respond_with接受一个 block 。

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

关于ruby-on-rails - Rails JSON 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3985368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com