sea*_*apy 4 ruby ruby-on-rails
我把我的批处理文件放在lib文件夹中并使用rails db配置,像这样的active-record.
require "#{File.dirname(__FILE__)}/../config/environment.rb"
class Batch
def hello
Message.new do |t|
t.title = "hello"
t.save
end
end
end
batch = Batch.new
batch.hello
Run Code Online (Sandbox Code Playgroud)
当执行批处理时
ruby lib/batch.rb
Run Code Online (Sandbox Code Playgroud)
在开发环境中没关系
但生产环境仍然保存开发数据库......
我如何设置rails_env batch.rb这样
ruby lib/batch.rb RAILS_ENV=production
Run Code Online (Sandbox Code Playgroud)
初始化Rails环境,而不是放置
require "#{File.dirname(__FILE__)}/../config/environment.rb"
Run Code Online (Sandbox Code Playgroud)
使用script/runner该-e选项启动批处理文件并指定环境
例如
script/runner -e production lib/batch.rb
Run Code Online (Sandbox Code Playgroud)
我认为以上是The Rails编写和执行脚本的方式,需要初始化Rails框架才能工作.正如中微子所说,另一种选择是在命令前加上RAILS_ENV = value,例如
$ RAILS_ENV=production lib/batch.rb
Run Code Online (Sandbox Code Playgroud)
这是在执行命令之前设置环境变量的标准shell功能.