我有这样的代码
class Author < ApplicationRecord
has_many :books, dependent: :destroy
end
class Book < ApplicationRecord
belongs_to :author
end
[在创建生成迁移时,我没有使用任何关键字来生成外键关联。但是我看到关于在structure.sql中添加外键的alter sql语句。如何以及为什么?
仅在模型中设置关联不会以任何方式更改架构,除非您通过迁移实际创建books.author_id列,否则此代码将仅给出未定义的列错误。
[使用author:belongs_to
或author:references
(它们是别名)运行模型生成器的确会向迁移以及模型中的belongs_to :author
关联添加外键列。
# rails g model book title:string author:belongs_to
class CreateBooks < ActiveRecord::Migration[6.0]
def change
create_table :books do |t|
t.string :title
t.belongs_to :author, null: false, foreign_key: true
t.timestamps
end
end
end
但是关联实际上并没有必须具有外键约束。如果使用author_id:bigint
运行迁移,则关联将起作用,但是您将没有外键约束来保证引用完整性。
另一方面,在生成器中使用books:has_many
会产生错误的迁移,因为has_many
关联不是数据库列。