创建于ActiveRecord的外键约束 [英] Creating foreign key constraints in ActiveRecord

查看:129
本文介绍了创建于ActiveRecord的外键约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建在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

但schema.rb和发展sqlite3的数据库没有任何迹象显示外键约束是建立与level_id领域。这是我必须从ActiveRecord的或者Rails做手工分开?我错过了一步?

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?

使用Rails 3.2.8

Using Rails 3.2.8

推荐答案

您不需要一个外键约束的ActiveRecord正确地映射关系。您可以使用 有Rails应用程序确保数据完整性验证。

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的迁移不提供佣工创建外键。您可以创建自己的SQL在迁移的限制或使用该外国人宝石。外国人将提供辅助方法的迁移创建约束:

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)

这篇关于创建于ActiveRecord的外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆