1

While developing my Rails app, I've been manually seeding its database with sample data. However, after I run rake db:migrate:reset I need to re-seed everything, which is tedious.

How can I get rake to seed the database for me?

The relevant model is generated in this migration:

class CreateKeyRecords < ActiveRecord::Migration
  def change
    create_table :key_records, :id => false do |t|
      t.string :name
      t.integer :parentID, :limit => 8
      t.primary_key :ID
      t.integer :accesses, :limit => 8
      t.integer :dt
      t.integer :hour
    end
    change_column :key_records, :ID, 'bigint'
  end
end

Currently, I'm seeding the db by directly altering the app's database in mysql, with the command:

LOAD DATA LOCAL INFILE '/tmp/input.tsv' INTO TABLE key_records (name, parentID, ID, accesses) SET dt=20141231, hour=23;

where input.tsv has the form:

key   1    2    9493878

How might I get rake to do this 'manual seeding' for me?

m81
  • 2,217
  • 5
  • 31
  • 47

1 Answers1

2

I don't think there's a "rails-ey" way of doing this, but you should be able to run a SQL statement in seeds.rb. You can run raw SQL statements against your database with ActiveRecord::Base.connection.execute. Your seed file would look something like this:

stmt = "LOAD DATA LOCAL INFILE '/tmp/input.tsv' 
    INTO TABLE key_records (name, parentID, ID, accesses) 
    SET dt=20141231, hour=23;"

ActiveRecord::Base.connection.execute stmt

You would then call it with rake db:seed.

Sculper
  • 756
  • 2
  • 12
  • 24
  • It didn't work :( I think the issue is that by default `LOAD DATA LOCAL INFILE` is disabled, but I don't know how to enable it in rails (I enabled it in regular mysql with [this post](http://stackoverflow.com/questions/10762239/mysql-enable-load-data-local-infile)). Do you know how I might enable it in Rails? – m81 Aug 12 '15 at 17:43
  • 1
    Add `local_infile: true` to your database.yml and see if that works - also, make sure the user your app is using has appropriate permissions. – Sculper Aug 12 '15 at 18:10