10

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.

Gary S. Weaver
  • 7,966
  • 4
  • 37
  • 61

2 Answers2

10

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

Gary S. Weaver
  • 7,966
  • 4
  • 37
  • 61
  • thx work perfect. Only change I need to do is the renamed file, because I use sometimes `scaffold` (this search schema with the regexp //schema[^/]*.rb$ ). I change `File.rename(File.expand_path('../db/schema.rb', __FILE__), File.expand_path('../db/schema.backup.rb', __FILE__))` – inye Mar 28 '17 at 15:10
1

To get this to work for me, I had to sandwich the call like this:

ActiveRecord::Base.schema_format = :ruby
Rake::Task["db:schema:dump"].invoke
ActiveRecord::Base.schema_format = :sql

Thanks Gary for your suggestions.

cyrusg
  • 31
  • 2
  • Is this with Rails7? AFAIK there were some changes in this area in Rails7. – mu is too short Apr 24 '23 at 19:36
  • I'm not sure if the changes in Rails 7 would help reshape the solution...Based on what I'm reading here: https://blog.saeloun.com/2022/08/30/rails-db-schema-supports-schema-format-env/ – cyrusg May 18 '23 at 04:35