我在 Rails Controller 中返回 JSON 的标准机制是:
respond_to do |format|
format.html
format.json { render json: @cars }
end
有没有办法修改 @cars
JSON?特别是我只想在其中添加 4 个额外的字段。
更新:抱歉,我应该多解释一下。 @cars
包含 Car
对象的列表。我想向 JSON 中的每个 Car
对象添加 4 个字段。这对于特定 Controller 来说是唯一,所以我不想创建 as_json
方法,因为这会影响此类的其他 JSON。
最佳答案
您还可以使用以下内容添加自定义或嵌套字段:
class MyModel < ActiveRecord::Base
def as_json(options)
super(options).merge({
"custom" => "myvalue",
:name => self.name.titleize,
"result" => self.my_method(self.value1)
})
end
end
关于ruby-on-rails - 如何修改从 Rails Controller 返回的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21716337/