运行使用我的模型

时间:2015-06-02 13:42:07

标签: ruby-on-rails ruby

我有以下需要。

我有一个Rails Web应用程序。我需要编写一个脚本来读取excel文件,并调用我的模型的方法来填充数据库。

这不是问题。

我只是想知道:

有什么东西有点像seed.rb,我可以运行.rb文件,它只会进行更改吗?

喜欢:rails runmyfile myfile.rb

该文件将读取电子表格并输入数据。我会使用seed.rb,但这不会让我在服务器运行时添加内容。

5 个答案:

答案 0 :(得分:5)

尝试为其创建rake任务。然后只是

rake my_tasks:task_name

可以找到有关自定义rake任务的更多信息here

答案 1 :(得分:0)

rails runner是您正在寻找的。

$ bin/rails runner  -e staging myfile.rb

从您的控制台阅读使用权:

$ bin/rails runner
Usage: rails runner [options] [<'Some.ruby(code)'> | <filename.rb>]

    -e, --environment=name           Specifies the environment for the runner to operate under (test/development/production).
                                     Default: development

    -h, --help                       Show this help message.

Examples:
    rails runner 'puts Rails.env'
        This runs the code `puts Rails.env` after loading the app

    rails runner path/to/filename.rb
        This runs the Ruby file located at `path/to/filename.rb` after loading the app

You can also use runner as a shebang line for your executables:
    -------------------------------------------------------------
    #!/usr/bin/env /Users/xxx/rails/app/bin/rails runner

    Product.all.each { |p| p.price *= 2 ; p.save! }
    -------------------------------------------------------------

答案 2 :(得分:0)

您正在寻找rails runner,它会在您的rails环境中运行任何Ruby脚本,让您可以访问模型等。

$ echo 'puts "hi"' > test.rb
$ rails runner test.rb
hi

或者直接从命令行运行一个小片段。

$ rails runner 'puts "hi"'
hi

答案 3 :(得分:0)

我为此目的使用rails runner runner 直接运行一段代码,但具有完整的rails环境。如果你想运行一个脚本(假设你的脚本在“lib / myscript.rb”下),在rails-environment中运行:

rails runner lib/myscript.rb

如果要在特定环境中运行脚本,请使用-e参数:

rails runner -e development lib/myscript.rb

答案 4 :(得分:0)

您可以使用CSV库执行类似的操作,并将其合并到rake任务中:

desc "add models from csv file"
task :add_csv_models => :environment do
  require 'csv'
  CSV.foreach('path/to/your_file.csv') do |row|
    mod = YourModel.new(attribute_1: row[0], attribute_2: row[1])
      if mod.save
        printf "\nModel Saved"
      else
        # handle exception here
      end
  end
end

然后运行rake:add_csv_models 你必须调整属性和行索引,但这应该给你一般的想法。

相关问题