Tomas Romero
Tomas Romero

Reputation: 8698

Update DB schema without using migrations in rails

I'm looking for a command that updates the schema automatically, without having to write migrations files.

For example, when I start a Java Hibernate app, with some configuration, the DB schema is automatically built and updated.

Upvotes: 1

Views: 371

Answers (2)

knut
knut

Reputation: 27845

With Sequel you can

An example (with sqlite, but it's the same with other adapters)

First the normal start:

require "sequel"
DB = Sequel.sqlite(DB_NAME)

# create an items table
DB.create_table :items do
  primary_key :id
  String :name
  Float :price
end

# [....]

require "sequel"
DB = Sequel.sqlite('test.db')

# create an items table
DB.create_table :items do
  primary_key :id
  String :name
  Float :price
end

Later you can modify the table:

DB.add_column :items, :valid_from, Date

The following modifications are possible (perhaps there are more):

  • add_column
  • add_index
  • create_view
  • drop_column
  • drop_index
  • drop_table
  • drop_view
  • rename_table
  • rename_column
  • set_column_default
  • set_column_type

In combination with rake you could do something like:

require "rake"
require "sequel"

task :connect do
  DB = Sequel.sqlite('test.db')
end

desc 'create an items table'
task :create_items => :connect do
  DB.create_table :items do
    primary_key :id
    String :name
    Float :price
  end
end

task :add_dates_to_items => :connect do
  #check if items exist is missing
  DB.add_column :items, :valid_from, Date
end

Remark: Migrations are a help to avoid wrong sequences of schema modifications. With Migrations you can define the correct sequence. The actual status is stored and you can downgrade.

Upvotes: 1

Peter Duijnstee
Peter Duijnstee

Reputation: 3779

As far as I know this isn't possible with ActiveRecord but if you don't mind changing ORM you could look into DataMapper instead.

With DM you define the 'properties' (attributes) of your models in the model code itself and then you can simply run rake db:automigrate to update the database's schema, e.g.

class Blog
  property :title,    String
  property :body,     Text
  property :user_id,  Integer, :required => true
end

Upvotes: 1

Related Questions