[ Pob's corner ]

Rails : Problème d’index trop long sur une migration ?

May 04, 2016 | about 1 minute read

En voulant créer une table de liaison entre deux autres dans un projet, nous avons rencontré un problème avec les index. Petit récap :

class CreateCategorieCritereCategorieProduit < ActiveRecord::Migration
  def change
    create_table :categorie_criteres_categorie_produits, id: false do |t|
      t.belongs_to :categorie_critere
      t.belongs_to :categorie_produit
    end
    add_index :categorie_criteres_categorie_produits, :categorie_critere_id"
    add_index :categorie_criteres_categorie_produits, :categorie_produit_id"
  end
end

En faisant un petit rake db:migrate qui va bien, on obtenait ceci :

==  CreateCategorieCritereCategorieProduit: migrating =========================
-- create_table(:categorie_criteres_categorie_produits, {:id=>false})
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Index name 'index_categorie_criteres_categorie_produits_on_categorie_critere_id' on table 'categorie_criteres_categorie_produits' is too long; the limit is 64 characters

Le problème vient du fait qu’en voulant respecter la convention Rails sur le bon nomage de notre table de liaison on se retrouve avec un index ayant un nom très long de 68 caractères. Or la limite autorisé par notre BDD est de 64. Pour contrer cela, on peut forcer un nom d’index différent en le précisant à la fin de notre migration comme ci-dessous :

class CreateCategorieCritereCategorieProduit < ActiveRecord::Migration
  def change
    create_table :categorie_criteres_categorie_produits, id: false do |t|
      t.belongs_to :categorie_critere
      t.belongs_to :categorie_produit
    end
    add_index :categorie_criteres_categorie_produits, :categorie_critere_id, name: "cat_crit_id"
    add_index :categorie_criteres_categorie_produits, :categorie_produit_id, name: "cat_prod_id"
  end
end

Et voilà !

Originally published at Sois-net.