Use of Migrations in Ruby on Rails

ruby, ruby-on-rails

Solution

Proposition 1 is false in at least two situations - you can use plugins like foreign_key_migrations to do the following:

def self.up
  create_table :users do |t|
    t.column :department_id, :integer, :references => :departments
  end
end

which creates the appropriate foreign key constraint in your DB.

Of course, you might have other things that you want to do in your DDL, in which case the second situation becomes more compelling: you're not forced to use the Ruby DSL in migrations. Try the `execute` method, instead:

def self.up
  execute 'YOUR SQL HERE'
end

With that, you can keep the contents of your SQL scripts in migrations, gaining the benefits of the latter (most prominently the `down` methods, which you didn't address in your original question) and retaining the lower-level control you prefer.

Problem

I would like to confirm that the following analysis is correct: I am building a web app in RoR. I have a data structure for my postgres db designed (around 70 tables; this design may need changes and additions during development to reflect Rails ways of doing things. EG, I designed some user and role tables - but if it makes sense to use Restful Authentication, I will scrub them and replace with whatever RA requires. ). I have a shellscript which calls a series of .sql files to populate the empty database with tables and initial data (eg, Towns gets pre-filled with post towns) as well as test data (eg, Companies gets a few dummy companies so I have data to play with). for example: ``` CREATE TABLE towns ( id integer PRIMARY KEY DEFAULT nextval ('towns_seq'), county_id integer REFERENCES counties ON DELETE RESTRICT ON UPDATE CASCADE, country_id integer REFERENCES countries ON DELETE RESTRICT ON UPDATE CASCADE NOT NULL, name text NOT NULL UNIQUE ); ``` Proposition 0: Data lasts longer than apps, so I am convinced that I want referential integrity enforced at the DB level as well as validations in my RoR models, despite the lack of DRYNESS. Proposition 1: If I replace the script and sql files with Migrations, it is currently impossible to tell my Postgres database about the Foreign Key and other constraints I currently set in SQL DDL files within the migration code. Proposition 2: The touted benefit of migrations is that changes to the schema are versioned along with the RoR model code. But if I keep my scripts and .sql files in railsapp/db, I can version them just as easily. Proposition 3: Given that migrations lack functionality I want, and provide benefits I can replicate, there is little reason for me to consider using them. So I should --skipmigrations at script/generate model time. My question: If Proposition 0 is accepted, are Propositions 1,2,3 true or false, and why? Thanks!

Original source