Ysal Ysal - 2 months ago 31
Ruby Question

How to populate my database using a JSON in Rails?

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.

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]

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!


Try placing your script file in Rail's script directory. Once you place it there add this to the top of your file:

#! /usr/bin/env ruby

require '../config/environment'

.......script code.....