Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using t.integer and t.reference to define foreign keys in a rails migration

Given two classes, Apple and Orange:

def class Apple < ActiveRecord::Base
  has_and_belongs_to_many :oranges
end

def class Orange < ActiveRecord::Base
  has_and_belongs_to_many :apples
end

What's the difference between using t.integer to define the foreign keys in the join table:

create_table :apples_oranges, :id => false do |t|
  t.integer :apple_id
  t.integer :orange_id
end

and using t.references to define the foreign keys in the join table:

create_table :apples_oranges, :id => false do |t|
  t.references :apple
  t.references :orange
end

I've seen both and they appear to be interchangeable. Just wanted to make sure there isn't some subtlety/magic that I'm missing.

Oh, and I'm on Rails 3.2 w/MySQL

like image 860
plainjimbo Avatar asked Apr 02 '12 21:04

plainjimbo


People also ask

Do you need foreign keys in rails?

Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.


1 Answers

http://guides.rubyonrails.org/migrations.html#special-helpers

No magic, per se. Makes the migration more readable, more railsy, if you will, and if you are using polymorphism, adds the type column as well. So, either, but references is better, just because it is.

like image 66
pduey Avatar answered Sep 17 '22 02:09

pduey