Rails从大量数据生成json的最佳方法是什么

时间:2013-12-18 01:24:36

标签: ruby-on-rails json api

我正在开发一个项目,它是移动应用的后端。

Una的API调用以json的形式返回大量数据,生成json需要很多。

现在,我正在预处理数据以生成包含所有信息和

的哈希
Places.each do |item|

      place = item.place

      place.discounts.each do |discount|
        response_item = {
            :id => place.id,
            :latitude => item.latitude,
            :longitude => item.longitude,
            :name => place.name,
            :url_image => place.img,
            :stars => 0,
            :is_habitue => false,#is_habitue,
            :discount => {
                :id => discount.id,
                :title => discount.title,
                :description => discount.description,
                :raw_title => discount.raw_title,
                :expiration => discount.expiration
            }
        }

        categories = []
        place.categories.each do |category|
          categories.append ({
              :name => category.name,
              :label => category.label
          })
        end
        response_item[:categories] = categories

        benefits = []
        discount.benefits.each do |benefit|
          benefits.append ({
            :benefit_type => benefit.benefit_type,
            :label => benefit.label
          })
        end
        response_item[:benefits] = benefits

        processed_places.append response_item
      end
end
render :json => {:places=>processed_places}, :status=>200

我需要大约1.4秒来处理2700个结果,但是生成json需要6秒多。

感谢

1 个答案:

答案 0 :(得分:0)

也许你可以试试RABL。它有很棒的功能:)