14

如何在 ActiveRecord 中创建外键?我的模型中有以下内容:

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 之外,这是我必须手动执行的操作吗?我错过了一步吗?

使用 Rails 3.2.8

4

5 回答 5

15

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

Rails 迁移不提供创建外键的助手。您可以为迁移中的约束创建自己的 SQL 或使用Foreigner Gem。Foreigner 将提供帮助方法来在迁移中创建约束:

add_foreign_key(:students, :levels)
于 2012-09-14T16:41:43.840 回答
13

如果您有 rails >= 4.2 并使用mysqlmysql2postgresql适配器,那么您可以add_foreign_key在迁移中使用该方法,如下所示:

# add a foreign key to `articles.author_id` referencing `authors.id`
add_foreign_key :articles, :authors

API 参考

于 2015-01-02T21:51:13.447 回答
3

这是内置在 Rails 中的,你不需要 Foreigner。请参阅此处的第 3.6 节外键:http: //edgeguides.rubyonrails.org/active_record_migrations.html

于 2015-03-10T18:55:07.023 回答
2

在模型中添加belong_tohas_many行使 Rails 知道它们之间的关系并生成辅助方法,但不会在数据库级别创建 FK。为此,您需要创建并运行迁移:

rails g migration add_level_id_to_students level_id:integer

然后 rake db:migrate

如果要生成带有外键部分的模型,可以使用references快捷方式: rails g model Student name:string level:references

查看Rails 指南以获取更多信息!

于 2012-09-14T16:43:14.230 回答
2
   $ rails generate migration AddStudentRefToLevels student:references

这应该是这样的

class AddStudentRefToLevels < ActiveRecord::Migration
  def change
    add_reference :levels, :student, index: true
  end
end

取自这里http://guides.rubyonrails.org/migrations.html#creating-a-migration

于 2013-10-10T20:20:33.540 回答