How do I create foreign keys in ActiveRecord? I have something like the following in my models:
class Student < ActiveRecord::Base
attr_accessible :name, :level_id
belongs_to :level
end
class Level < ActiveRecord::Base
attr_accessible :number
has_many :students
end
But the schema.rb and development sqlite3 database don’t have any indication foreign key constraints were setup with the level_id field. Is this something I have to do manually apart from ActiveRecord or Rails? Did I miss a step?
Using Rails 3.2.8
You do not need a foreign key constraints for ActiveRecord to correctly map the relationships. You can use validations to have the Rails app ensure data integrity.
Rails migration do not provider helpers to create foreign keys. You can create your own SQL for the constraint in the migration or use the the Foreigner Gem. Foreigner will provide helper methods for creating constraints in a migration: