I am trying to populate my database by parsing a JSON file and running a ruby script once that would create instances of my models and save them in my database.
我试图通过解析JSON文件并运行ruby脚本来填充数据库,该脚本将创建模型实例并将它们保存到数据库中。
Example Script:
示例脚本:
require 'json'
require 'byebug'
file = File.read('players.json')
data_hash = JSON.parse(file)
data_hash_size = data_hash['Name'].size
data_hash.each_with_index do |i|
@student = student.new
@student.name = data_hash['Name'][i]
@student.college_year = data_hash['Cl.'][i]
@student.save!
end
My question is, where do I put such a script in my app and how do I connect it to the models I want to create instances of to populate the database? Currently, it's giving me an error: undefined local variable or method student for main:Object (NameError). I even tried require 'app/models/student.rb'
and it still doesn't work. I currently have the script placed in the app home directory (with the README file and such). Any help would be appreciated, thanks!
我的问题是,在我的应用程序中,我应该把这样的脚本放在哪里?我如何将它连接到我想要创建的模型实例来填充数据库?目前,它给了我一个错误:main:Object (NameError)的未定义局部变量或方法student。我甚至尝试过“应用/模特/学生”。rb,它仍然不起作用。我目前将脚本放置在应用程序主目录(带有README文件等)中。如有任何帮助,我们将不胜感激,谢谢!
1 个解决方案
#1
2
Try placing your script file in Rail's script
directory. Once you place it there add this to the top of your file:
尝试将脚本文件放在rails的脚本目录中。一旦你把它放在那里,把它添加到你的文件顶部:
#! /usr/bin/env ruby
require '../config/environment'
.......script code.....
#1
2
Try placing your script file in Rail's script
directory. Once you place it there add this to the top of your file:
尝试将脚本文件放在rails的脚本目录中。一旦你把它放在那里,把它添加到你的文件顶部:
#! /usr/bin/env ruby
require '../config/environment'
.......script code.....