[英]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 my_script
时,我收到了这个错误:
rake aborted!
uninitialized constant MyModel
What am I doing wrong? 我究竟做错了什么?
Also, should I name my file my_script.rb
or my_script.rake
? 另外,我应该将文件命名为my_script.rb
或my_script.rake
吗?
Just require the file. 只需要文件。 I do this in one of my rake tasks (which I name my_script.rake
) 我在我的一个rake任务中执行此操作(我将其命名为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. 但更好的设计是让rake任务简单地调用辅助方法。 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. 好处是可以更轻松地扫描可用的rake任务,更容易调试,并且rake任务运行的代码变得非常可测试。 You could add a rake_helper_spec.rb
file for example. 例如,您可以添加rake_helper_spec.rb
文件。
# /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: 为了让它工作,我所要做的就是将我的要求置于任务规范之上,然后只需声明:environment
标志:
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. 我require 'active_record'
甚至require
我的模型。
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. 我也遇到了Nokogiri的问题,我所做的就是从我的文件顶部删除它作为一个require
并将其添加到我的Gemfile中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.