Take the 2-minute tour ×

I would to populate the database (MySQL) with some dummy entries as the application starts.

I created:

class DatabaseInitializer
  def populate_database

in lib/database_initializer.rb.

I understand that all files in the lib directory should have been loaded automatically.

Question 1: Is there any command to see a list of all files that have been loaded ?

Then, in controllers/main_controller.rb I have:

require 'lib/database_initializer.rb'
class MainController < ApplicationController
  def initialize
  def index

But, I got the following error:

LoadError in MainController#index
no such file to load -- lib/database_initializer.rb

Question 2: Why it cannot find database_initializer.rb ?

Question 3: Is this "Rails enough" way to pre-populate a database ? Would you do this otherwise (put database_initializer.rb in other place, call DatabaseInitializer.new.populate_database from other place, e.t.c.) ?

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

Question 1


Question 2

# the 'lib' directory is already added to the load
# path in the Rails initialization process, so simply:
require 'database_initializer`

Question 3

# db/seeds.rb
c = Company.create! :name => 'ABC Inc.'
p = Person.create! :name => 'Jeremy', :company => c

$ rake db:seed
share|improve this answer
Thanks! This really helps. One more question: what is the difference between create! and create in your code ? –  Misha Moroshko Dec 9 '10 at 4:47
create! throws an exception if it fails whereas create just returns false. It's a common pattern in ActiveRecord however generally in ruby a bang_method! indicates that the method alters the receiver directly rather than returning a new object. See Array#reverse and Array#reverse! –  noodl Dec 9 '10 at 10:41
Thanks! Is it always recommended to use create! rather than create when creating records in database (I do want to know if something goes wrong) ? –  Misha Moroshko Dec 11 '10 at 4:38
add comment

When requiring files from ruby you generally drop the file extension. Try require database_initializer. lib/ was briefly removed from the load path in rails-3 but I think it's back now. If not, see config.autoload_paths in config/application.rb.

However, I think this is probably a bad idea in general. If you need to ensure that you always have a consistent and immutable set of data available to your app, why not just define it in ruby in a model?

Also, there is already a mechanism for adding seed data in rails. See db/seeds.rb and the command rake db:seed

share|improve this answer
Thanks, I will definitely use db/seeds.rb from now! –  Misha Moroshko Dec 9 '10 at 4:47
add comment

For any file in lib, you should only have to use: require 'database_initializer'.

share|improve this answer
add comment

Your Answer


