Ruby-on-rails 迁移中的 t.references 与模型中的belongs_to?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16309742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
t.references in the migration vs belongs_to in the model?
提问by Dragos C.
I was reading the Rails Guides and I found these lines of code:
我正在阅读 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
I also read Michael Hartl's book, Rails Tutorial and I did not find anything about the "t.references" used in the code above. What does it do? In Michael's book I used has_many and belongs_to relations in the model and nothing in the migrations(not event t.belongs_to).
我还阅读了 Michael Hartl 的书 Rails 教程,但我没有找到关于上面代码中使用的“t.references”的任何信息。它有什么作用?在迈克尔的书中,我在模型中使用了 has_many 和belongs_to 关系,而在迁移中没有使用任何关系(不是事件 t.belongs_to)。
回答by Tim Sullivan
This is a fairly recent addition to Rails, so it may not be covered in the book you mention. You can read about it in the migration sectionof Rails Guides.
这是 Rails 的一个相当新的补充,所以你提到的那本书可能没有涵盖它。您可以在Rails 指南的迁移部分阅读它。
When you generate using, say,
当您使用生成时,例如,
rails generate model Thing name post:references
... the migration will create the foreign key field for you, as well as create the index. That's what t.referencesdoes.
...迁移将为您创建外键字段,并创建索引。这就是t.references它的作用。
You could have written
你可以写
rails generate model Thing name post_id:integer:index
and gotten the same end result.
并得到相同的最终结果。
回答by cortex
See this sectionof Rails Guides.
请参阅Rails 指南的这一部分。
In your case, t.referencescreates a post_idcolumn in your commentstable. That means that Comment belongs to Post, so in Commentmodel you have to add belongs_to :postand in Post model: has_many :comments.
在您的情况下,在您的表中t.references创建一post_id列comments。这意味着 Comment 属于 Post,因此在Comment模型中您必须添加belongs_to :post并在 Post 模型中:has_many :comments。

