最近在項目里嘗試使用seeds做staging的數據。而不是靠手動添加。
原因有三個,一是為了數據的可控性。二是,目前后臺開發滯后于前臺開發。三是,通過創建數據了解項目。
認為開發最開始的階段,由于需求不明確,用最“友善”的數據就可以了,隨著大體框架的確認,再做進一步的改進。
隨著開發的進行,遇到了以下問題(沒使用seeds的經驗,囧)。
- 隨著數據增多,變得不好管理。
- 當數據更新的時候,seeds 應該是可以被反復執行的。
- staging部署后,是否應該被自動執行
為了解決這些問題,做了一個簡單的調查,筆記如下。
如何理解seeds data?
Minimum amount data to get your app fully functional -- railscasts 179
Initial data to the database is called seeding, and is distinct from migrations, which are for managing changes to the schema.
Use the seed for staging. -- Engineering Long-Lasting Software
Tips
使用
find_or_create_by
和delete_all
,保證seeds文件可以被反復執行。-
使用單獨的文件存放
比如一個movie有兩個字段,name,director想要導入的數據有
Good Will Hunting | Ben Affleck
Star Trek | J.J. Abrams
......把這些數據放到一個單獨的文件內,是個比較不錯的選擇。
可以在seed內使用fixtures和factory_girl
# for fixtures
require "active_record/fixtures"
Fixtures.create_fixtures("#{Rails.root/test/fixtures}", "operating_systems")
# for factory_girl
# read more: http://stackoverflow.com/a/17118006/2477886
require 'factory_girl_rails'
10.times do
FactoryGirl.create :user
end
兩個相關的gem
- populator
提供了一些DSL,在就是把文件放到了rake task內。覺得挺好的,但不是必須的。 - seed-fu
對原有的seeds做了極大的改進。
特性有:-
更好的語法
User.seed(:id, { :id => 1, :login => "jon", :email => "jon@example.com", :name => "Jon" }, { :id => 2, :login => "emily", :email => "emily@example.com", :name => "Emily" } )
-
更好的組織種子數據的方式
seed_fu可以根據model將種子數據放在不同的文件內。
比如:db/fixtures/users.rb db/fixtures/movies.rb
并且有相應的generator。
默認有輸出
如果是seeds的話需要puts。可以和Capistrano集成。
容易使用,學習成本較低。
-
建議
使用seeds時,應注意到seeds是會被持續改進和反復執行的,所以應該使用find_or_create_by, delete_all之類的一些技巧。
建議使用seed_fu,使用容易,并且會帶來很大的便利。