gpt4 book ai didi

ruby-on-rails - 如何使用 Rails 生成迁移以添加引用?

转载 作者:行者123 更新时间:2023-12-04 07:37:21 25 4
gpt4 key购买 nike

我目前正在使用 Rails 4.2.4。事情是当我跑
rails g migration AddCategoryRefToArticles category:references命令,

它生成了以下迁移

def change
add_reference :articles, :category, index: true, foreign_key: true
end

由于某种原因导致 category_id作为整数字段而不是预期的 t.references。
create_table "articles", force: :cascade do |t|
t.string "title"
t.integer "category_id"
end

add_index "articles", ["category_id"], name: "index_articles_on_category_id", using: :btree

为什么会这样?

最佳答案

add_reference只是一个方便的助手来生成一个整数字段,该字段遵循要在关联中使用的命名约定。自 schema.rb映射数据库模式,预计您会看到特定的数据类型而不是更高级别的抽象。

我不知道为什么你会期待 t.references ,但你的期望是错误的。这在 add_reference 中也有解释。文档。

Create a user_id integer column

add_reference(:products, :user)

关于ruby-on-rails - 如何使用 Rails 生成迁移以添加引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34587707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com