Rails使用camelCase渲染json对象

Aug*_*aza 5 ruby api json ruby-on-rails

我在一个简单的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
Run Code Online (Sandbox Code Playgroud)

这个问题是,生成的json具有以下格式:

{
  id:2,
  name: 'Simple account',
  cash_flows: [
    {
      id: 1,
      amount: 34.3,
      description: 'simple description'
    },
    {
      id: 2,
      amount: 1.12,
      description: 'other description'
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我需要我生成的json是camelCase('cashFlows'而不是'cash_flows')

提前致谢!!!

Aug*_*aza 11

按照@TomHert的推荐,我使用了JBuilder和可用的配置:

键可以使用key_format!自动格式化,这可以用于将标准ruby_format中的键名转换为camelCase:

json.key_format! camelize: :lower
json.first_name 'David'

# => { "firstName": "David" }
Run Code Online (Sandbox Code Playgroud)

您可以使用类方法key_format(例如,在environment.rb中)全局设置它:

Jbuilder.key_format camelize: :lower
Run Code Online (Sandbox Code Playgroud)

谢谢!!!