Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails migration: only for schema change or also for updating data?

I'm a junior Rails developer and at work we faced the following problem:

Needed to update the value of a column only for one record. What we did is creating a migration like this:

class DisableAccessForUser < ActiveRecord::Migration
  def change
    User.where(name: "User").first.update_column(:access, false)
  end
end

Are migrations only for schema changes?

What other solutions do you suggest?

PS: I can only change it with code. No access to console.

like image 537
Webspirit Avatar asked Sep 02 '25 10:09

Webspirit


1 Answers

The short version is, since migrations are only for schema changes, you wouldn't want to use them to change actual data in the database.

The main issue is that your data-manipulating migration(s) might be ignored by other developers if they load the DB structuring using either rake db:schema:load or rake db:reset. Both of which merely load the latest version of the structure using the schema.rb file and do not touch the migrations.

As Nikita Singh also noted in the comments, I too would say the best method of changing row data is to implement a simple rake task that can be run as needed, independent of the migration structure. Or, for a first time installation, the seed.rb file is perfect to load initial system data.

Hope that rambling helps.

Update

Found some documentation in some "official" sources:

  • Rails Guide for Migrations - Using Models in your Migrations. This section gives a description of a scenario in which data-manipulation in the migration files can cause problems for other developers.
  • Rails Guide for Migrations - Migrations and Seed Data. Same document as above, doesn't really explain why it is bad to put seed or data manipulation in the migration, merely says to put all that in the seed.rd file.
  • This SO answer. This person basically says the same thing I wrote above, except they provide a quote from the book Agile Web Development with Rails (3rd edition), partially written by David Heinemeier Hansson, creator of Rails. I won't copy the quote, as you can read it in that post, but I believe it gives you a better idea of why seed or data manipulation in migrations might be considered a bad practice.
like image 104
Paul Richter Avatar answered Sep 05 '25 00:09

Paul Richter