views:

42

answers:

2

Hi All,

I have a rails project where I need to add some default values to the database table. I want to know the best way of doing these (im using rails 2.3.3 which doesn't have seed.rb file :()

1 - Creating a sql script

2 - creating a migration

3 - creating a rake task

4 - other (Please explain)

thanks in advance

cheers

sameera

A: 

Take a look at seed-fu.

John Topley
hi Johnthanks, will checkoutcheerssameera
sameera207
A: 

In current stable version of Rails (2.3.8) there is rake task db:seed, which execute code in db/seeds.rb file. In that file you can load you data by directly executing Rails code (News.create :title => "test" ...), or use any other method you prefer.

I prefer to load data from fixtures, cause fixtures can be used in tests later. I'm using rspec, so my fixtures stored in spec/fixtures/ directory.

You can use next code to make fixtures from existing sql tables:

def make_fixtures(tablenames, limit = nil)
  sql = "SELECT * FROM %s"
  sql += " LIMIT #{limit}" unless limit.nil?
  dump_tables = tablenames.to_a
  dump_tables.each do |table_name|
    i = "000"
    file_name = "#{RAILS_ROOT}/spec/fixtures/#{table_name}.yml"
    puts "Fixture save for table #{table_name} to #{file_name}"
    File.open(file_name, 'w') do |file|
      data = ActiveRecord::Base.connection.select_all(sql % table_name )
      file.write( data.inject({}) do |hash, record|
        hash["#{table_name}_#{i.succ!}"] = record
        hash
      end.to_yaml )
    end
  end
end

In db/seeds.rb you can load from fixtures:

require 'active_record/fixtures'

[ "classifiers", "roles", "countries", "states", "metro_areas" ].each do |seed|
  puts "Seeding #{seed}..."
  Fixtures.create_fixtures(File.join(Rails.root, "spec", "fixtures"), seed)
end
Alexey