Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If using the this option in config/application.rb:

config.active_record.schema_format = :sql

then when you do:

rake db:migrate

it only dumps the db/structure.sql. I know it isn't using the db/schema.rb since it is using the :sql option, but how can you make rake db:migrate generate db/schema.rb also?

We need that because RubyMine 4.5 and IntelliJ IDea 11 use db/schema.rb for autocompletion of columns.

like image 774
Gary S. Weaver Avatar asked Nov 30 '12 14:11

Gary S. Weaver


People also ask

How do you regenerate a schema rb?

If you run a rake -T it will list all possible rake tasks for your Rails project. One of them is db:schema:dump which will recreate the schema.

How does rake db migrate work?

A migration means that you move from the current version to a newer version (as is said in the first answer). Using rake db:migrate you can apply any new changes to your schema. But if you want to rollback to a previous migration you can use rake db:rollback to nullify your new changes if they are incorrectly defined.

What is schema rb?

The schema. rb serves mainly two purposes: It documents the final current state of the database schema. Often, especially when you have more than a couple of migrations, it's hard to deduce the schema just from the migrations alone. With a present schema.

What is are the default column columns that rails will generate while migrating?

By default, the generated migration will include t. timestamps (which creates the updated_at and created_at columns that are automatically populated by Active Record).


1 Answers

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.)

like image 142
Gary S. Weaver Avatar answered Sep 27 '22 22:09

Gary S. Weaver