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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With