Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails script access model

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

like image 792
jack Avatar asked Aug 03 '26 13:08

jack


1 Answers

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.

like image 119
miaout17 Avatar answered Aug 06 '26 04:08

miaout17



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!