在我的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
到目前为止,这个方法工作正常。我想要的是在每个元素的索引中添加此处索引(作为结果对象的ID)。
我该如何实现?
答案 0 :(得分:2)
没有开箱即用的方法,但是您可以使用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。