我在简单的 Rails API 中有以下控制器代码:
class Api::V1::AccountsController < ApplicationController
def index
render json: Account.all
end
def show
begin
render json: Account.includes(:cash_flows).find(params[:id]), include: :cash_flows
rescue ActiveRecord::RecordNotFound => e
head :not_found
end
end
end
问题在于,生成的 json 的格式为:
{
id:2,
name: 'Simple account',
cash_flows: [
{
id: 1,
amount: 34.3,
description: 'simple description'
},
{
id: 2,
amount: 1.12,
description: 'other description'
}
]
}
我需要生成的 json 是驼峰命名法(“cashFlows”而不是“cash_flows”)
提前致谢!!!
遵循推荐@TomHert https://stackoverflow.com/users/1290852/tom-hert, 我用了JBuilder https://github.com/rails/jbuilder和可用的配置:
可以使用 key_format! 自动格式化键,这可用于将键名从标准 ruby_format 转换为camelCase:
json.key_format! camelize: :lower
json.first_name 'David'
# => { "firstName": "David" }
您可以使用类方法 key_format 全局设置它(例如,从environment.rb内部):
Jbuilder.key_format camelize: :lower
谢谢!!!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)