Search code examples
ruby-on-railspostgresqlruby-on-rails-4apartment-gem

Create constraints in rails migrations


I have a migration that create a named constraint

execute(%Q{
  ALTER TABLE dreamflore_clients
    ADD CONSTRAINT unique_clients UNIQUE( client, no_adresse );
})

But in schema.rb, rails turn this part into an index

add_index "dreamflore_clients", ["client", "no_adresse"], name: "unique_clients", unique: true, using: :btree

The problem is we are using Apartment and newly created tenants have an index instead of the constraint and we are using the postgreSQL feature ON CONFLICT ON CONSTRAINT

For now the solution is to rollback some migrations and migrate again, but this is a really dirty hack

How to stop rails creating this index?


Solution

  • Have you tried using structure.sql instead of schema.rb by running rake db:structure:dump?

    schema.rb has some limitations regarding syntax and switching to structure.sql ought to solve this issue.

    You can make the switch to structure.sql permanent by adding config.active_record.schema_format = :sql to environment.rb.