Kerby82
Kerby82

Reputation: 5146

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.

Upvotes: 2

Views: 93

Answers (2)

Maciej Małecki
Maciej Małecki

Reputation: 2745

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.

Upvotes: 1

DiegoSalazar
DiegoSalazar

Reputation: 13531

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

Upvotes: 2

Related Questions