0

I am trying to import a CSV file into an existing table in my SQLite3 database on a rails project.

I have tried the correct answer on this solution but I get the error:

uninitialised constant Object::Points

Here is my data.csv file which is in my main directory:

Item,2003,2004,2005,2006,2007
AA2,43,34,23,52,24
TT2,48,39,29,23,29

Here is my model file which is saved in app\models\points.rb:

class Points < ActiveRecord::Base
  attr_accessible :Item, :2003, :2004, :2005, :2006, :2007
end

Here is my migration file which is saved in db\migrate\20130709123346_create_points.rb:

class CreatePoints < ActiveRecord::Migration
  def change
    create_table :points do |t|
      t.varchar(255) :Item
      t.integer :"2003"
      t.integer :"2004"
      t.integer :"2005"
      t.integer :"2006"
      t.integer :"2007"  

      t.timestamps
    end
  end
end

Below is what I have tried based on the correct solution linked above:

  1. Created new file called import.rake and saved it in lib\tasks\import.rake:

    require 'csv'    
    
    csv_text = File.read('data.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      Points.create!(row.to_hash)
    end
    
  2. Then I ran bundle exec rake import.rake in the command line.

After running this I get the error:

uninitialised constant Object::Points

I must be missing something which causes this error. What am I doing wrong?

Community
  • 1
  • 1
LogiKal
  • 49
  • 3
  • 12

1 Answers1

1

You need to define the content of your import.rake as an actual task. Also, as your code stands, rake knows nothing about your Rails environment, which is why it can't find Points. For example

require 'csv'

namespace :import do
  task :points => :environment do
    csv_text = File.read('data.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      Points.create!(row.to_hash)
    end
  end
end

Then from the command line

bundle exec rake import:points

The => :environment dependency on the task is what kicks off the Rails environment.

deefour
  • 34,974
  • 7
  • 97
  • 90
  • Thanks for the help. When I run the task it now returns the error `syntax error, unexpected keyword_end, expecting $end`. I removed the first `end` in the task but then it then returns a slightly different error: `syntax error, unexpected $end, expecting keyword_end`. – LogiKal Jul 15 '13 at 14:34
  • @LogiKal as it stands that's outside the scope of this question. There is no block closure issue in the code I've provided above. I unfortunately can't fix syntax errors for code I can't see. – deefour Jul 15 '13 at 14:39
  • Do you have any idea where I could find the code which is causing the problem? – LogiKal Jul 15 '13 at 14:44
  • The console will tell you the exact line the error is occurring. That should give you a good idea. Beyond that though, you're better off creating a new question with the related code, as I simply would be guessing otherwise. – deefour Jul 15 '13 at 14:48