Home on_delete cascade do not run in mysql
Reply: 0

on_delete cascade do not run in mysql

MAPLUZ
1#
MAPLUZ Published in 2018-01-02 10:56:42Z

I used a helper module found on the web to add options on my integrity constraints between my table projects and 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)

Here are the models and migration of my 2 tables clients and projects:

clients

class CreateClients < ActiveRecord::Migration
  def change
    create_table :clients do |t|
       t.string  :ident
       t.string  :lastname, :default=>''
       t.text    :comment    
       # foreign key
      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

projects

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

When I look at the structure of my customers table in phpmyadmin, CASCADE is not good !! capture of phpmyadmin do you have an idea ?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300971 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO