【问题标题】:Import JSON into Heroku Rails app then store in database将 JSON 导入 Heroku Rails 应用程序,然后存储在数据库中
【发布时间】:2012-05-29 21:09:58
【问题描述】:

我有一个托管在 Heroku 上的 Rails 3.2 应用程序。 我想尝试避免手动输入每个数据的所有数据 新纪录。他们是我让我的 Rails 应用程序查看的简单方法吗? 像这样的 JSON 文件(除了 MUCH LARGER)并将该信息解析为 数据库?

[   {
    "name": "Sierra Mist – Small Cup",
    "wwpplus": "5",
    "ssize": "451g",
    "calories": "190",
    "tfat": "0",
    "protein": "0",
    "fiber": "0",
    "carbs": "50",
    "restaurant_id": "12"
},
{
    "name": "Vanilla Shake regular",
    "wwpplus": "13",
    "ssize": "425g",
    "calories": "480",
    "tfat": "15",
    "protein": "14",
    "fiber": "0",
    "carbs": "74",
    "restaurant_id": "12"
},
{
    "name": "Vanilla Shake small",
    "wwpplus": "11",
    "ssize": "340g",
    "calories": "380",
    "tfat": "12",
    "protein": "11",
    "fiber": "0",
    "carbs": "60",
    "restaurant_id": "12"
}]

【问题讨论】:

    标签: ruby-on-rails json postgresql heroku import


    【解决方案1】:

    您可以在 db/seeds.rb 文件中解析它:

    records = JSON.parse(File.read('path/to/file.json'))
    records.each do |record|
      ModelName.create!(record)
    end
    

    然后heroku run rake db:seed

    【讨论】:

    • 我不知道 rails 能做到这一点 刚刚添加了 JSON GEM 将这些行添加到我的种子文件中 rake db:seed Boom 127 条记录添加了谢谢 MAN
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多