Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating foreign key constraints in ActiveRecord

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

like image 321
at. Avatar asked Sep 14 '12 16:09

at.


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.

What is a foreign key Ruby?

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.

What is the difference between Has_one and Belongs_to?

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.


2 Answers

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)
like image 139
mguymon Avatar answered Oct 07 '22 14:10

mguymon


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

like image 36
Segfault Avatar answered Oct 07 '22 15:10

Segfault