简体   繁体   中英

Script execution upon ruby on rails app restart

I'm developing an app in ruby on rails (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.

Sounds like you can place this one-off script in a rails migration. Run this command in the terminal:

rails generate migration NameOfMyDataMigration

Replace NameOfMyDataMigration with a name that makes sense to you

That will create a new migration script in db/migrate that will look something like this:

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

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. There are several arguments for each of them.

The main advantage over the migration is that Rake task is not dependent on the code. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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