简体   繁体   中英

How do I access one of my models from within a ruby script in the /lib/ folder in my Rails 3 app?

I tried putting my script in a class that inherited from my model, like so:

class ScriptName < MyModel

But when I ran rake my_script at the command-line, I got this error:

rake aborted!
uninitialized constant MyModel

What am I doing wrong?

Also, should I name my file my_script.rb or my_script.rake ?

Just require the file. I do this in one of my rake tasks (which I name my_script.rake )

require "#{Rails.root.to_s}/app/models/my_model.rb"

Here's a full example

# lib/tasks/my_script.rake

require "#{Rails.root.to_s}/app/models/video.rb"

class Vid2 < Video
  def self.say_hello
    "Hello I am vid2"
  end
end

namespace :stuff do
  desc "hello"
  task :hello => :environment do
    puts "saying hello..."
    puts Vid2.say_hello
    puts "Finished!"
  end
end

But a better design is to have the rake task simply call a helper method. The benefits are that it's easier to scan the available rake tasks, easier to debug, and the code the rake task runs becomes very testable. You could add a rake_helper_spec.rb file for example.

# /lib/rake_helper.rb
class Vid2 < Video
  def self.say_hello
    "Hello I am vid2"
  end
end

# lib/tasks/myscript.rake
namespace :stuff do
  desc "hello"
  task :hello => :environment do
    Vid2.say_hello
  end
end

All I had to do to get this to work was put my requires above the task specification, and then just declare the :environment flag like so:

task :my_script => :environment do
 #some code here
end

Just by doing that, gave me access to all my models. I didn't need to require 'active_record' or even require my model.

Just specified environment and all my models were accessible.

I was also having a problem with Nokogiri, all I did was removed it from the top of my file as a require and added it to my Gemfile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM