YSA
YSA

Reputation: 879

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]
  @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!

Upvotes: 1

Views: 563

Answers (1)

Dan Rubio
Dan Rubio

Reputation: 4907

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.....

Upvotes: 2

Related Questions