在迁移VS belongs_to的模型t.references? [英] t.references in the migration vs belongs_to in the model?

查看:218
本文介绍了在迁移VS belongs_to的模型t.references?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了Rails的指南,我发现了code这几行:

I was reading the Rails Guides and I found these lines of code:

  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

我也看过迈克尔·哈特尔的书,Rails的教程,我没有发现有关在code上面所用的t.references任何东西。 它做什么?在迈克尔的书,我在模型中,并没有在移民(不活动t.belongs_to)。

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).

推荐答案

这是一个相当新的除了Rails的,所以它可能不会被覆盖在书中你提到的。

This is a fairly recent addition to Rails, so it may not be covered in the book you mention.

在生成使用,比方说,

rails generate model Thing name post:references

...迁移将创建外键字段的你,以及创建索引。这就是 t.references 一样。

您可以写

rails generate model Thing name post_id:integer:index

和得到相同的结果。

这篇关于在迁移VS belongs_to的模型t.references?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆