【问题标题】:What is belongs_to creates in rails migrations and in the database structure?什么是belongs_to 在rails 迁移和数据库结构中创建的?
【发布时间】:2018-02-23 21:06:52
【问题描述】:

我对rails 中的belongs_to 和外键感到困惑。当我们在 rails 迁移中使用 belongs_to 时,它似乎在子表上创建了一个外键,我们可以从父表访问该外键。但是,在 rails 文档中,有一种情况在一个列中同时使用两者。

create_table :accounts do |t|
  t.belongs_to :supplier, index: { unique: true }, foreign_key: true
  # ...
end

有人能解释一下这种情况,并解释一下 belongs_to 和 foreign_key: true 到底是做什么的吗?

【问题讨论】:

    标签: ruby-on-rails database-design rails-migrations


    【解决方案1】:

    t.belongs_to :suppliersupplier_id 添加到accounts

    index: { unique: true } 为该列创建一个database index

    foreign_key: true 为该列创建一个foreign key constraint

    我建议你阅读Active Record Migrations — Ruby on Rails Guides

    索引加快了数据检索操作。

    外键有助于维护referential integrity

    【讨论】:

    • 所以 t.belongs_to :supplier 等于 t.integer :supplier_id?
    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2021-10-27
    • 1970-01-01
    • 2012-09-18
    • 2012-01-15
    • 2011-02-11
    相关资源
    最近更新 更多