如何运行使用 Rails 模型的 Ruby 任务? [英] How do I run Ruby tasks that use my Rails models?
问题描述
我有一个带有一些基本模型的 Rails 应用程序.该网站显示从其他来源检索的数据.所以我需要编写一个 Ruby 脚本来在我的数据库中创建新实例.我知道我可以用测试钩子做到这一点,但我不确定这是否有意义.
I have a Rails app with some basic models. The website displays data retrieved from other sources. So I need to write a Ruby script that creates new instances in my database. I know I can do that with the test hooks, but I'm not sure that makes sense here.
我不确定这个任务应该是什么样子,如何调用它,或者它应该放在我的源代码树中的哪个位置(lib\tasks?).
I'm not sure what this task should look like, how I can invoke it, or where it should go in my source tree (lib\tasks?).
例如,这是我的第一次尝试:
For example, here's my first try:
require 'active_record'
require '../app/models/mymodel.rb'
test = MyModel.new
test.name = 'test'
test.save
这会失败,因为它无法连接到数据库.这对我的新手大脑来说是有道理的,因为大概 Rails 在幕后做了所有神奇的工作来设置所有这些东西.那么如何设置我的小脚本?
This fails because it can't get a connection to the database. This makes sense in a vague way to my newbie brain, since presumably Rails is doing all the magic work behind the scenes to set all that stuff up. So how do I set up my little script?
推荐答案
我同意上面的答案,但你必须在你的任务中包含 => :environment 否则它不会加载 Rails 环境.
I agree with the answer above but you have to include => :environment in your task or it will not load the Rails environment.
例如
namespace :send do
namespace :trial do
namespace :expiry do
desc "Sends out emails to people who's accounts are about to expire"
task :warnings => :environment do
User.trial_about_to_expire.has_not_been_notified_of_trial_expiry.each do |user|
UserMailer.deliver_trial_expiring_warning(user)
user.notified_of_trial_expiry = true
user.save
end
end
end
end
end
这篇关于如何运行使用 Rails 模型的 Ruby 任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!