问题描述
在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
不能在播种前进行必要的迁移
解决方法
如果您检出rails db:setup
的{{3}},则会发现db:setup
没有运行db:migrate
创建数据库,加载架构,并使用种子数据进行初始化(使用db:reset首先也删除数据库)
db:schema:load
将schema.rb
中当前存在的内容加载到数据库中。