Home Rails中以脚本的形式执行某段代码
Post
Cancel

Rails中以脚本的形式执行某段代码

参考:http://stackoverflow.com/questions/9757261/how-do-i-run-a-ruby-file-in-a-rails-environment 

1. 新建一个 文件: script/test_hi.rb

# 运行方式:
#
# $ bundle exec ruby script/test_hi.rb
#
ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'production'
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'rails'
require 'rubygems'

puts 'hihihi'
puts User.all

2. 运行: $ bundle exec ruby script/test_hi.rb

This post is licensed under CC BY 4.0 by the author.