Reputation: 454
i need a script to be able to access my model. I found a post about this which suggested doing
require "#{ENV['RAILS.root']}/config/environment.rb"
in the top of my script. then i can run ruby script/my_script.rb to run it. But this gives me the error
/Users/my_name/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': no such file to load -- /config/environment.rb (LoadError)
what am i doing wrong
Upvotes: 2
Views: 1244
Reputation: 4875
I think ENV['RAILS.root']
will be set after the environment is loaded. You can try
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
However, a more commonly used idiom is writing Rake task. For example, create a file named lib/tasks/mytask.rake
:
task :mytask => :environment do
# Do something with your model
end
Then execute rake mytask
. The environment
task will automatically load the Rails environment.
Upvotes: 10
Reputation: 454
I found my own answer. forget what i said to include in the top. put this instead
ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development'
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
Upvotes: 0