on_delete cascade n'est pas pris en compte dans mysql

20 views
Skip to first unread message

devmapluz

unread,
Dec 30, 2017, 11:04:56 AM12/30/17
to Railsfrance
bonjour à tous

j'ai utilisé un module helper trouvé sr le web pour rajouter des options sur mes contraintes d'intégrité entre ma table projects et clients :

module MigrationHelper
  
  def add_foreign_key(from_table, from_column, to_table, options = {})
    
    to_column = options.fetch(:to_column, 'id')
    suffix = options[:suffix]
    on_delete = options[:delete]
    on_update = options[:update]

    on_delete = 'SET NULL' if on_delete == :set_null
    on_update = 'CASCADE' if on_update == :cascade

    constraint_name = "fk_#{from_table}_#{to_table}"
    constraint_name += "_#{suffix}" unless suffix.nil?
    sql = "ALTER TABLE #{from_table} "
    sql += "ADD CONSTRAINT #{constraint_name} "
    sql += "FOREIGN KEY (#{from_column}) REFERENCES #{to_table}(#{to_column}) "
    sql += "ON DELETE #{on_delete} " if on_delete
    sql += "ON UPDATE #{on_update}" if on_update
    execute sql
  end

  def remove_foreign_key(from_table, to_table, suffix = nil)
    constraint_name = "fk_#{from_table}_#{to_table}"
    constraint_name += "_#{suffix}" unless suffix.nil?

    # note, you may have to use DROP KEY here - see MySQL docs for details
    execute "ALTER TABLE #{from_table} DROP FOREIGN KEY #{constraint_name}"
  end
end
ActiveRecord::Migration.extend(MigrationHelper)


Voici ma table clients et son modele :

class CreateClients < ActiveRecord::Migration
  def change
    create_table :clients do |t|
      t.string  :ident
      t.string  :lastname, :default=>''
      t.text    :comment    
        # cles etrangeres
      t.belongs_to :project, :index=>true
      t.timestamps           
    end
      add_foreign_key :clients, :project_id, :projects, on_delete: :cascade
  end
  
end

class Client < ActiveRecord::Base
  belongs_to  :project
end


et voici ma table projects et son modele

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string :name
      t.timestamps
    end
  end
end

class Project < ActiveRecord::Base
  has_many :clients
end



or quand je regarde la structure de ma table clients dans phpmyadmin, cascade n'est pas pris en compte



avez vous une idée ?

merci

Ma Config
windows 7
wamp server 3.0.6 32 bits
rails 4.17
ruby 2.2
Reply all
Reply to author
Forward
0 new messages