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
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.
Foreign key relationships specify how tables relate to each other and indicate relationships between tables. RubyMine recognizes foreign key relationships in your database schema and uses them to construct JOIN clauses.
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
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:
add_foreign_key(:students, :levels)
If you have rails >= 4.2 and using the mysql
, mysql2
, or postgresql
adapter, then you can use the add_foreign_key
method in your migration like this:
# add a foreign key to `articles.author_id` referencing `authors.id`
add_foreign_key :articles, :authors
API Reference
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