steel
steel

Reputation: 12520

Rails - Keep a table out of structure.sql during migrations

It is straightforward to ignore tables when your schema format is :ruby, but is there a way to do it when your schema format is :sql?

Ideally something like this in environment.rb:

ActiveRecord::SQLDumper.ignore_tables = ['table_name']

After a quick perusal through the AR source code it looks unpromising.

Upvotes: 10

Views: 1041

Answers (2)

Zach Parks
Zach Parks

Reputation: 136

For the sake of people landing here after Googling this problem in 2022: As of this PR the structure.sql dump should respect the ignore_tables configuration of ActiveRecord::SchemaDumper. If you're using a regular schema.rb, this option can be a mix of strings and regexes; However, if you're using a structure.sql, it will only take strings according to the docs.

In any case, you can add an initializer to modify the list of ignored tables however you need. In my case, I have a number of backup tables that are created when certain risky operations are performed, and I'd like to exclude those from the structure.sql. Adding this initializer solved it for me:

# config/initializers/ignore_tables.rb

backup_tables = ActiveRecord::Base.connection.tables.select do |t|
  t.match?(/_backup_.*$/)
end

ActiveRecord::SchemaDumper.ignore_tables += backup_tables

Upvotes: 5

Marc Lainez
Marc Lainez

Reputation: 3080

There is currently no way to do this, when the schema format is set to :sql, Rails doesn't go through the regular SchemaDumper but instead uses the tasks in ActiveRecord::Tasks::PostgreSQLDatabaseTasks to do the dump, check it out here.

The code is quite straightforward. I came up with a simple patch for ActiveRecord that should work as expected. It relies on setting the tables to ignore in your database.yml file. It basically adds the following code:

ignore_tables = configuration['ignore_tables']
unless ignore_tables.blank?
  args += ignore_tables.split(',').map do |table|
    "-T #{table}"
  end
end

I just submitted a pull request to rails with those changes. In case you'd want to test it.

Upvotes: 5

Related Questions