简体   繁体   English

Ruby on Rails应用重启后执行脚本

[英]Script execution upon ruby on rails app restart

I'm developing an app in ruby on rails (rails v4). 我正在开发Rails上的ruby应用程序(rails v4)。

I made some changes on the model and the data need to be modified by a script once the application in production is updated and restarted. 我对模型进行了一些更改,一旦生产中的应用程序更新并重新启动,就需要通过脚本修改数据。

Is there a neat way to say to the rail server to execute a script (just once) when the code is updated. 在更新代码时,是否有一种巧妙的方法可以告诉铁路服务器执行脚本(一次)。

It's like when you add a gem in the Gemfile and the server won't start until you do a bundle update. 就像您在Gemfile中添加gem一样,直到您进行捆绑更新,服务器才会启动。

Sounds like you can place this one-off script in a rails migration. 听起来您可以将这个一次性脚本放入Rails迁移中。 Run this command in the terminal: 在终端中运行以下命令:

rails generate migration NameOfMyDataMigration

Replace NameOfMyDataMigration with a name that makes sense to you 用对您有意义的名称替换NameOfMyDataMigration

That will create a new migration script in db/migrate that will look something like this: 这将在db/migrate中创建一个新的迁移脚本,如下所示:

class NameOfMyDataMigration < ActiveRecord::Migration
  def change
    # your data modification logic
  end
end

When you deploy that to production you can execute it with: 将其部署到生产中时,可以使用以下命令执行它:

rake db:migrate

That migration will only run once. 该迁移将只运行一次。

Learn more about Rails migrations here: http://guides.rubyonrails.org/v4.2/active_record_migrations.html 在此处了解有关Rails迁移的更多信息: http : //guides.rubyonrails.org/v4.2/active_record_migrations.html

While Diego's answer is correct, I would like to point out another approach. 尽管迭戈的答案是正确的,但我想指出另一种方法。 Basically there are two ways to update data. 基本上有两种更新数据的方法。 The first one is migrations as described in Diego's answer. 第一个是迭戈答案中所述的迁移。 Another one is Rake task. 另一个是Rake任务。 There are several arguments for each of them. 每个都有几个参数。

The main advantage over the migration is that Rake task is not dependent on the code. 与迁移相比,主要优点是Rake任务不依赖于代码。 As the result you don't need to squash migrations or build database from schema file when new developer joins the project. 结果,当新的开发人员加入该项目时,您无需压制迁移或从架构文件构建数据库。

You should take a look at the post written by Elle Meredith about data migrations in Rails and then pick the best method for you. 您应该看一下Elle Meredith撰写的有关Rails中数据迁移的文章 ,然后为您选择最佳方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM