7.Migration e foreing key

Di seguito riporto il codice per creare una migration delle tabelle job e branch con relazione 1 a molti utilizzando le foreing key.

Vi sono alcune sintassi che sono diventate obsolete, altre invece sono di uso corrente in rails 3, dunque vediamo come fare una buona implementazione delle chiavi esterne senza incorrere in errori:

Prima di tutto abbiamo bisogno di una gemma (foreign) che possiamo installare aggiungendo al Gemfile la seguente riga:

gem 'foreigner'

Ricordiamo che foreigner supporta i seguenti db:

  • mysql2
  • postgres
  • sqlite (foreign key methods are a no-op)

Una volta generato lo scaffold (vedi sezione scaffold) andiamo sui model e modifichiamoli come segue:

class Branch < ActiveRecord::Base
  belongs_to :job
end

class Job < ActiveRecord::Base
  has_many :branchs, dependent: :delete_all
end

Una volta completata la modifica dei modelli possiamo passare alla definizione della migration:

change_table :comments do |t|
  t.foreign_key :posts, dependent: :delete
end
class CreateJobs < ActiveRecord::Migration
  def change create_table :jobs do |t| 
  t.string "description",  
  t.datetime "created_at" 
  t.datetime "updated_at"    
  t.integer "branch_id", :null => true, :references =>  :branches 
end 
  add_foreign_key "jobs", "branches", :name => "fk_jobs_branches", :dependent => :delete 
  end 
end

Altre implementazioni come ad esempio:

add_foreign_key(:jobs, :branches,column: 'branche_id',name: 'fk_jobs_branches')

Oppure

 
add_index "jobs", ["branche_id"], :name => "fk_jobs_branches"

Non sono funzionanti,obsolete o deprecate.
In alternativa è possibile utilizzare la seguente sintassi che però risulta un pò più lunga:

add a foreign key #execute <<-SQL 
   ALTER TABLE jobs 
     ADD CONSTRAINT fk_jobs_branches 
     FOREIGN KEY (branche_id) 
     REFERENCES branches(id) 
     on delete set null on update cascade 
     SQL
Tothebit

About Tothebit

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site