gpt4 book ai didi

ruby-on-rails - 迁移中的 t.references 与模型中的belongs_to?

转载 作者:行者123 更新时间:2023-12-03 10:25:57 25 4
gpt4 key购买 nike

我正在阅读 Rails 指南,我发现了这些代码行:

  class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :post

t.timestamps
end

add_index :comments, :post_id
end
end

我还阅读了 Michael Hartl 的书 Rails 教程,但我没有找到关于上面代码中使用的“t.references”的任何信息。
它有什么作用?在迈克尔的书中,我在模型中使用了 has_many 和belongs_to 关系,而在迁移中没有使用任何关系(不是事件 t.belongs_to)。

最佳答案

这是 Rails 的一个相当新的补充,所以你提到的那本书可能没有涵盖它。您可以在 the migration section 中阅读有关它的信息Rails 指南。

当您使用生成时,例如,

rails generate model Thing name post:references

...迁移将为您创建外键字段,并创建索引。就是这样 t.references做。

你可以写
rails generate model Thing name post_id:integer:index

并得到相同的最终结果。

关于ruby-on-rails - 迁移中的 t.references 与模型中的belongs_to?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16309742/

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