0

Rails Tips #002

Posted in RoR at January 7th, 2008 /

由於 Rails 2 已經推出了一段日子,我也來寫寫 Rails 2 要注意的地方。

Rails 2.0 is RESTful by default

我也來講講人稱 Sexy migration 的 ActiveRecord Migration,在 Rails 2.0 之前,migration 是長成這樣子的︰

1
2
3
4
5
6
7
8
9
10
11
12
13
# db/migrate/001_create_customers.rb
class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.column :first_name, :string
      t.column :last_name, :string
    end
  end
 
  def self.down
    drop_table :customers
  end
end

到了 Rails 2.0,migration 就變成這樣子︰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# db/migrate/001_create_customers.rb
class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.string :first_name
      t.string :last_name
 
      t.timestamps
    end
  end
 
  def self.down
    drop_table :customers
  end
end

除此之外,還新增了一個 rake task︰rake db:rollback,在以前,要 rollback 就只有用 rake db:migrate VERSION=xx 來做,新的 rake task 比較好用,不需要再去理會 version。

Published in RoR

No Responses to “Rails Tips #002”

Leave a Reply