1

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!

1 Answer 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:

#! /usr/bin/env ruby

require '../config/environment'

.......script code.....
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's working now. If I want to run this script only once to populate the database, do I just run it through rails console (or Heroku console when I deploy it) or is there a more elegant way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.