如何在jbuilder中添加每个元素的索引

How to add index of each element in jbuilder

在我的 Rails 应用程序中,我执行以下操作以使用 jbuilder 将我的所有数据导出为 JSON 字符串:

index.json.jbuilder

json.array!(@react_exp) do |exp|
  json.id(**INDEX HERE**)
  json.createdAt((exp.created_at.to_f * 1000).to_i) 
  json.updatedAt((exp.updated_at.to_f * 1000).to_i) 
  json.extract! exp, :description
  json.categoryId(exp.category_id)
  json.extract! exp, :value
  json.day(exp.day.strftime('%Q').to_i)
end

到目前为止一切正常。我想要的是添加每个元素的索引,其中显示 INDEX HERE(作为结果对象的 ID)。

我怎样才能做到这一点?

没有开箱即用的方法,但您可以使用 Ruby each_with_index 方法。

json.array! @react_exp.each_with_index do |exp, index|
  json.id index
  json.createdAt((exp.created_at.to_f * 1000).to_i) 
  json.updatedAt((exp.updated_at.to_f * 1000).to_i) 
  json.extract! exp, :description
  json.categoryId(exp.category_id)
  json.extract! exp, :value
  json.day(exp.day.strftime('%Q').to_i)
end

阅读此 GitHub Issue