Tuesday, September 25, 2007

Rails migration plugins from Mr.err

sexy db migration:


class UpdateYourFamily < ActiveRecord::Migration
create_table :updates do |t|
t.column :user_id, :integer
t.column :group_id, :integer
t.column :body, :text
t.column :type, :string

t.column :created_at, :datetime
t.column :updated_at, :datetime
end

def self.down
drop_table :updates
end
end

Into this:

class UpdateYourFamily < ActiveRecord::Migration
create_table :updates do
foreign_key :user
foreign_key :group

text :body
string :type

timestamps!
end

def self.down
drop_table :updates
end
end

Using this:
SVN:
$ ./script/plugin install \ svn://errtheblog.com/svn/plugins/sexy_migrations

auto db migration, change this:

ActiveRecord::Schema.define(:version => 1) do
create_table :posts do |t|
t.string :title
t.text :body
end
end

into

ActiveRecord::Schema.define(:version => 1) do
create_table :posts do |t|
t.string :title
t.text :body
t.integer :published
end

create_table :comments do |t|
t.string :name, :url
t.text :body
t.integer :post_id
end
end

and run:
$ rake db:auto:migrate

it’ll execute the following:

-- add_column("posts", :published, :integer)
-> 0.0096s
-- create_table(:comments)
-> 0.0072s

Pretty slick. Run the task again and nothing will happen, just like regular migrations, but change the file and the plugin will do its best to figure out what you’ve done.
and support index:

ActiveRecord::Schema.define(:version => 1) do
create_table :posts do |t|
t.string :title
t.text :body
t.integer :published
end

add_index :posts, :published

create_table :comments do |t|
t.string :name, :url
t.text :body
t.integer :post_id
end
end

Followed by:

$ rake db:auto:migrate
-- add_index("posts", ["published"])
-> 0.0216s


ActiveRecord::Schema.define(:version => 1) do
create_table :posts do |t|
t.string :title
t.text :body
t.integer :published
end

# add_index :posts, :published

create_table :comments do |t|
t.string :name, :url
t.text :body
t.integer :post_id
end
end

And auto-migrate again:

$ rake db:auto:migrate
-- remove_index("posts", {:name=>"index_posts_on_published"})
-> 0.0187s

Check it Out:
Warehouse: http://plugins.require.errtheblog.com/browser/auto_migrations
SVN: svn://errtheblog.com/svn/plugins/auto_migrations

No comments :