Dragos C.
Dragos C.

Reputation: 621

t.references in the migration vs belongs_to in the model?

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

Upvotes: 31

Views: 49253

Answers (2)

Tim Sullivan
Tim Sullivan

Reputation: 16898

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.

Upvotes: 33

cortex
cortex

Reputation: 5224

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.

Upvotes: 8

Related Questions