在 Rails 6 上,我希望rake db:setup
执行db:create
,db:migrate
并且db:seed
我只有一个数据模型,并且它的表的记录创建是写在db/seeds.rb
# db/seeds.rb
require 'csv'
csv_text = File.read(Rails.root.join('lib', 'seeds', 'seed_first_table.csv'))
csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
csv.each_with_index do |row, index|
cr = CatProfile.new
puts "row #{index} saved"
end
puts "There are now #{CatProfile.count} rows in the table"
database.yml
还有一个新的用户凭证,它是通过sudo -u postgres createuser -s new_user
但rake db:setup
返回:
Created database 'my_application_development'
Created database 'my_application_test'
my_application/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /my_application/config/application.rb to limit the frameworks that will be loaded.
其中sudo -u postgres psql
确实创建了数据库,但没有关系(没有种子表)
当我跑步时rails db:migrate
== 20201103153526 CreateCatProfiles: migrating =================================
-- create_table(:cat_profiles)
-> 0.0091s
== 20201103153526 CreateCatProfiles: migrated (0.0092s) ========================
然后当我rake db:setup
第二次运行时:
Database 'my_application_development' already exists
Database 'my_application_test' already exists
row 0 saved
row 1 saved
...
row 1719 saved
There are now 1720 rows in the table
注意到数据库从一开始就已经存在,rake db:setup
但现在它能够为表播种
我不明白为什么rake db:setup
第一次运行在播种前没有进行必要的迁移