2011-03-17 59 views
5

我正在寫一個Rails遷移創建一個表:Rails的時間戳:updated_on/created_on與created_at /的updated_at

create_table(TABLE, :options => FEDERATED_TABLE_CONFIG % TABLE) do |table| 
    table.timestamps 
    table.string :country_tld 
end 

這將導致如下表所示:

CREATE TABLE `sites` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `created_at` datetime DEFAULT NULL, 
    `updated_at` datetime DEFAULT NULL, 
    `country_tld` varchar(255) DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=FEDERATED DEFAULT CHARSET=utf8 CONNECTION='mysql://foo:[email protected]/baz/sites' 

可悲的是,我的外國數據源使用老式的Rails updated_oncreated_on列作爲其時間戳。當然,我可以解決這個問題:

create_table(TABLE, :options => FEDERATED_TABLE_CONFIG % TABLE) do |table| 
    table.datetime :created_on, :updated_on 
    table.string :country_tld 
end 

如果有仍然使用時間戳和得到我想要的行爲微不足道的方式,我很樂意聽到它。不,我不認爲monkey-patching ActiveRecord::Timestamp是一個微不足道的方法,因爲這隻會影響一次遷移。 ;)

回答

8

我不完全確定你的問題在這裏? ActiveRecord::Timestamp將使用與_at版本相同的created_onupdated_on列(參見第84行88)。

順便說一句,您不需要遍歷數組來生成一行內的日期時間。使用這個來代替:

table.datetime :created_on, :updated_on 
+0

謝謝,我不知道,你可以同時創建多個列與[「性感語法」(http://guides.rubyonrails.org/migrations.html#creating-一張桌子)。 – 2011-03-17 14:03:13

+1

我的問題是:我可以使用'#timestamps'助手來創建舊式的列嗎? – 2011-03-17 14:05:22

5

軌道源timestamps是:

def add_timestamps(table_name) 
    add_column table_name, :created_at, :datetime 
    add_column table_name, :updated_at, :datetime 
end 

所以你可以看到有沒有辦法可以自定義列名。說實話,最好的方法就是你建議的那個。我個人避免這樣的東西:

%w{created_on updated_on}.each {|col| table.datetime col.to_sym } 

而只是寫出來的實際add_column命令,它更詳細一點也更容易閱讀。

相關問題