Why "require" cannot find a file in Ruby on Rails 3 application?
I would to populate the database (MySQL) with some dummy entries as the application starts.
I created:
class DatabaseInitializer
def populate_database
...
end
end
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
Database开发者_运维技巧Initializer.new.populate_database
end
def index
...
end
end
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.) ?
Question 1
$LOADED_FEATURES
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
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
For any file in lib, you should only have to use: require 'database_initializer'
.
精彩评论