Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import data into rails?

I have a Rails 3 application with a User class, and a tab-delimited file of users that I want to import.

How do I get access to the Active Record model outside the rails console, so that I can write a script to do

require "???active-record???"

File.open("users.txt", "r").each do |line|
    name, age, profession = line.strip.split("\t")
    u = User.new(:name => name, :age => age, :profession => profession)
    u.save
end

Do I use the "ar-extensions" gem, or is there another way? (I don't particularly care about speed right now, I just want something simple.)

like image 685
grautur Avatar asked Sep 13 '10 20:09

grautur


1 Answers

You can write a rake method to so. Add this to a my_rakes.rake file in your_app/lib/tasks folder:

  desc "Import users." 
  task :import_users => :environment do
    File.open("users.txt", "r").each do |line|
      name, age, profession = line.strip.split("\t")
      u = User.new(:name => name, :age => age, :profession => profession)
      u.save
    end
  end

An then call $ rake import_users from the root folder of your app in Terminal.

like image 119
Yannis Avatar answered Oct 28 '22 13:10

Yannis