Ruby 想请教一个 ror 的问题

a2338123 · April 16, 2022 · Last by a2338123 replied at April 18, 2022 · 595 hits

在做 michael hartl 的 railstutorial 教程时出现了一个问题,好像是外键冲突?以下是我的代码

class CreateMicroposts < ActiveRecord::Migration[7.0]
  def change
    create_table :microposts do |t| 
      t.text :content
      t.references :user, foreign_key: true
      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at]
  end
end



像是 test fixture 里面的数据引用了不存在的对象。

Reply to Rei

感谢!!!!!!

t.references :user, foreign_key: true 这句是在数据库里做了外键,也就是每条 micropost 数据 user_id 字段对应的 user 在数据库里必须存在。

一般我们建表时候不用 foreign_key,直接t.references :user,在 model 里,指明关联关系

class Micropost < ApplicationRecord
  belongs_to :user
end
Reply to yfscret

是的没错,我后来也发现原来是 fixture 里面的 user 字段不存在。 也就是说 foreign_key 这句代码省略也可以😄

foreign_key 主要看业务,需不需要数据库外健保证数据一致性。例如订单引用了产品,但是产品被删除了,订单处理就会出异常,这样就需要外健保护。

Reply to a2338123

不是代码省略的问题 是 foreign_key 的使用场景问题 foreign_key 是个强约束的限制 主要作用是保持数据的一致性和完整性 你需要自己判断是否需要外键作为约束

Reply to Rei

明白了 通俗易懂

Reply to zj0713001

知道了😀

You need to Sign in before reply, if you don't have an account, please Sign up first.