31

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

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

Dragos C.
  • 621
  • 2
  • 7
  • 15
  • Possible duplicate of http://stackoverflow.com/questions/7788188/what-is-the-difference-between-t-belongs-to-and-t-references-in-rails – sameers Jun 29 '14 at 22:51
  • @sameers not really, the other one is asking about the `belongs_to` in the migrations not in the models – Abdelrahman Elkady Nov 13 '15 at 18:59

2 Answers2

33

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 section of Rails Guides.

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.references does.

You could have written

rails generate model Thing name post_id:integer:index

and gotten the same end result.

Tim Sullivan
  • 16,808
  • 11
  • 74
  • 120
  • But is it still acceptable to add a foreign key the old way?( by using belongs_to IN THE MODEL) – Dragos C. Apr 30 '13 at 22:13
  • 2
    That's adding a foreign key to the model, not to the underlying database. You'll need to do that anyway. If you generate your model using `post:references`, though, the generator will add `belongs_to :post` for you automatically. – Tim Sullivan Apr 30 '13 at 22:36
  • 4
    Incidentally, you can actually use `belongs_to` in the migration - it's an alias of `references` – MrTheWalrus May 01 '13 at 01:31
  • 3
    No, the book had been updated since this feature was added, but Michael felt references was too much magic, and teaches each element separately. Personally I think it's a mistake not to at least mention this shortcut once the basic concepts have been taught, as db relationships are core to building pretty much any Rails app, so it's something done repeatedly. – Matt Sep 24 '14 at 19:46
  • In the question above, is the defined `post_id` index superfluous here? – Jonathan Jun 25 '20 at 10:13
8

See this section of Rails Guides.

In your case, t.references creates a post_id column in your comments table. That means that Comment belongs to Post, so in Comment model you have to add belongs_to :post and in Post model: has_many :comments.

cortex
  • 5,036
  • 3
  • 31
  • 41