Ruby-on-rails 通过 rake 将 structure.sql 加载到 rails 数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23091817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load a structure.sql into a rails database via rake
提问by locoboy
rake db:schema:loadwill load a schema.rbfile into a rails database. Is there a way to load a structure.sqlfile into the database through rake or do I just need to do this manually?
rake db:schema:load将schema.rb文件加载到 rails 数据库中。有没有办法structure.sql通过 rake将文件加载到数据库中,或者我只需要手动执行此操作?
回答by Tsutomu
Use rake db:structure:load, which will load db/structure.sql.
使用rake db:structure:load,这将加载db/structure.sql.
[Update]
[更新]
If you want to load another file, you can specify its path via
如果你想加载另一个文件,你可以通过指定它的路径
SCHEMAenvironment variable (Rails 5.0 or later)DB_STRUCTUREenvironment variable (Rails 4.x)
SCHEMA环境变量(Rails 5.0 或更高版本)DB_STRUCTURE环境变量(Rails 4.x)
For example, run
例如,运行
rake db:structure:load SCHEMA=db/another.sql
or
或者
rake db:structure:load DB_STRUCTURE=db/another.sql
回答by nathanvda
Just use
只需使用
rake db:setup
which will use either schema.rbor structure.sqldepending on your configuration.
将使用schema.rb或structure.sql取决于您的配置。
回答by Joseph Lord
Use the database's own SQL load mechanism.
使用数据库自己的 SQL 加载机制。
For Postgres this should work (at least if the database exists and you don't need a password):
对于 Postgres,这应该可以工作(至少如果数据库存在并且您不需要密码):
psql -d databaseName < db/structure.sql
On Heroku where rake db:setup doesn't work as you can't create a database like that you can do this:
在 Heroku 上 rake db:setup 不起作用,因为您无法创建这样的数据库,您可以这样做:
heroku pg:psql < db/structure.sql
回答by JstRoRR
Once you load your schema, you can try:
加载架构后,您可以尝试:
rails dbconsole < structure.sql
OR
或者
rails db < structure.sql
回答by jpayne
Sometimes you want to load a file that is not the default db/structure.sql.
有时您想加载一个不是默认的文件db/structure.sql。
For rails 4.2 and earlier, use
对于 rails 4.2 及更早版本,请使用
DB_STRUCTURE=some_file.sql rake db:structure:load
DB_STRUCTURE=some_file.sql rake db:structure:load
As of rails 5 use
截至 Rails 5 使用
SCHEMA=some_file.sql rake db:structure:load
SCHEMA=some_file.sql rake db:structure:load
回答by Lenin Raj Rajasekaran
Make your seeds.rb file like:
使您的 seed.rb 文件像:
unless Rails.env.production?
connection = ActiveRecord::Base.connection
sql = File.read('db/structure.sql')
statements = sql.split(/;$/)
statements.pop # the last empty statement
ActiveRecord::Base.transaction do
statements.each do |statement|
connection.execute(statement)
end
end
end
来源。

