使用ActiveRecord拥有has_many和belongs_to是否在structure.sql中生成alter sql语句?

问题描述 投票:0回答:1

我有这样的代码

class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end

class Book < ApplicationRecord
  belongs_to :author
end

[在创建生成迁移时,我没有使用任何关键字来生成外键关联。但是我看到关于在structure.sql中添加外键的alter sql语句。如何以及为什么?

ruby-on-rails ruby activerecord rails-activerecord
1个回答
0
投票

仅在模型中设置关联不会以任何方式更改架构,除非您通过迁移实际创建books.author_id列,否则此代码将仅给出未定义的列错误。

[使用author:belongs_toauthor: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关联不是数据库列。

© www.soinside.com 2019 - 2024. All rights reserved.