Ruby on rails Rails活动记录:外键与引用

Ruby on rails Rails活动记录:外键与引用,ruby-on-rails,activerecord,foreign-keys,Ruby On Rails,Activerecord,Foreign Keys,这是我的密码 class CreatePosts < ActiveRecord::Migration[5.1] def change create_table :posts, id: :uuid do |t| t.string :name t.references :user, type: :uuid t.references :user, type: :uuid, foreign_key: true t.timest

这是我的密码

class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts, id: :uuid do |t|
      t.string :name

      t.references :user, type: :uuid
      t.references :user, type: :uuid, foreign_key: true    

      t.timestamps
    end
  end
end
有人能告诉我什么时候用外键吗

我在搜索这些时发现了类似的东西

t.references :makers, foreign_key: { to_table: :office }

在上述代码中,外键不正确。它引用了一些表。为什么会这样。

您可以检查的文档,它使用与相同的选项

因此,不同之处在于:

t、 引用:user,type::uuid-添加列而不添加约束

t、 引用:user,type::uuid,foreign\u key:true-添加列和外键约束。如果不指定外键,那么它将为false

外键:{to_table::table_name}-可以选择使用自定义名称而不是约定名称添加列

例如,在文档中:

添加\参考:产品,:供应商,外键:{到\表::公司}

所以,它将向表products添加一个列名称supplier_id,并添加一个外键来引用Firmines表

如果遵循约定名称,则需要添加名为firm_id而不是supplier_id的列。

foreign_key:true将创建外键约束,没有该约束,将只创建外键

要了解外键和外键约束之间的区别,请访问链接

指定外键:{to_table::office}将使外键引用office表

t.references :makers, foreign_key: { to_table: :office }