How to Make Rake Db:Migrate Generate Schema.Rb When Using :SQL Schema Format

How to make rake db:migrate generate schema.rb when using :sql schema format

To generate/update db/schema.rb even if using the :sql option, you can put this in your Rakefile:

Rake::Task["db:migrate"].enhance do
if ActiveRecord::Base.schema_format == :sql
Rake::Task["db:schema:dump"].invoke
end
end

That should be fine for IDea and RubyMine.

For others that just want the file for reference, you might want to rename it to something else like db/schema.rb.backup so it won't be confusing. To do that:

Rake::Task["db:migrate"].enhance do
if ActiveRecord::Base.schema_format == :sql
Rake::Task["db:schema:dump"].invoke
File.rename(File.expand_path('../db/schema.rb', __FILE__), File.expand_path('../db/schema.rb.backup', __FILE__))
end
end

(Note: Using ../ in paths in Rakefile because __FILE__ evaluates to a path that ends in /Rakefile.)

How to dynamically set schema_format for custom db rake tasks in Rails?

Try this:

  task :set_custom_db_config_paths do
ENV['SCHEMA'] = 'db_other/schema.rb'
Rails.application.config.paths['db'] = ['other']
Rails.application.config.paths['db/migrate'] = ['db_other/migrate']
Rails.application.config.paths['config/database'] = ['config/database_other.yml']
Rails.application.config.active_record.schema_format = :ruby
end

Note the last line setting Rails.application.config.active_record.schema_format = :ruby

Why does schema.rb update after I run db:migrate for Rails?

As far as I know schema can change after running rails db:migrate because of:

  1. A co-worker did not commit the schema.rb so when you fetched and run the migrations you get the diff
  2. A different DB version is running on your local machine. Based on db configuration schema may be changed accordingly.

Running git diff will help you to understand what is going.

`rake db:schema:dump` creates schema with empty system tables

There is hope:

ActiveRecord::SchemaDumper which does most of the heavy lifting supplies a singleton method for ignoring tables:

ActiveRecord::SchemaDumper.ignore_tables = ['MSreplication_objects', 'MSAnotherStupidSystemTable']

activerecord-sqlserver-adapter does not seem to supply its own rake task for dumping the schema (which it should) where this should have been done.



Related Topics



Leave a reply



Submit