Pra*_*rma 4 ruby ruby-on-rails
rails中"add_foreign_key"和"add_reference"方法有什么区别?
根据rails官方指南,我所理解的是它们都用于在两个表之间创建外键约束.
Mas*_*ano 19
(注:此答案基于 Rails 6.0。)
总之,add_reference( Refadd_column ) 是、add_index和add_foreign_key( Ref )的组合集合的缩写形式,默认情况下不添加数据库级外键。因此,当您想要实现足够简单的东西或(相反?)多态引用时,很方便。如果没有,请使用, 也许与 显式 结合使用。add_referenceadd_foreign_keyadd_index
举一个简单的例子,这两个(我认为)彼此等效:
add_reference :articles, :author, foreign_key: true
add_column :articles, :author_id, :bigint, null: true
add_foreign_key :articles, :authors
add_index :articles, :author_id
Run Code Online (Sandbox Code Playgroud)
以下是更详细的差异:
add_reference是引用(没有 的列名称_id,因此通常是单数),而 的第二个add_foreign_key参数是表名称(因此通常是复数)。add_reference,
foreign_key选项指定为非零。index: true是默认的,而索引是不相关的add_foreign_keynull: true是默认值(允许列为空),这与add_foreign_keypolymorphic: true仅在 Rails 中可用add_reference(它将在一个操作中创建 2 列;请参阅 Ref)。add_reference很大程度上更具包容性,接受更广泛的选项。对于has_one关联,禁止 null 的地方:
add_reference :products, :merchant, null: false, index: {unique: true}, foreign_key: {on_delete: :cascade}
Run Code Online (Sandbox Code Playgroud)
当一个表有 2 个外键列指向同一个表时:
add_foreign_key :products, :merchants, column: :seller_id
add_foreign_key :products, :merchants, column: :buyer_id
add_index :products, [:seller_id, :buyer_id], unique: true, name: 'index_my_name_shorter_than_64chars'
Run Code Online (Sandbox Code Playgroud)
add_foreign_key - 添加新的外键.from_table是具有键列的表,to_table包含引用的主键.
add_reference - 用作同时创建列,索引和外键的快捷方式.
什么是foreign key- 外键是表中的一个字段或一组字段,用于唯一标识另一个表中的行.
| 归档时间: |
|
| 查看次数: |
932 次 |
| 最近记录: |