bonjour à tous
j'ai utilisé un module helper trouvé sr le web pour rajouter des options sur mes contraintes d'intégrité entre mes tables projects et clients :
Voici les modèles et migration de mes 2 tables clients et projects :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 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)
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 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 endQuand je regarde la structure de ma table clients dans phpmyadmin, CASCADE n'est pas pris en compte
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13 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
Avez vous une idée ?
Merci par avance
Ma Config
- windows 7
- wamp server 3.0.6 32 bits
- rails 4.17
- ruby 2.2
Partager