Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 900
Dragos C. Avatar asked Apr 30 '13 22:04

Dragos C.


People also ask

What does T references do?

t. references tells the database to make a column in the table. foreign_key: true tells the database that the column contains foreign_key from another table. belongs_to tells the Model that it belongs to another Model.

How would you choose between Belongs_to and Has_one?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

Does rails have one relationship?

Ruby on Rails ActiveRecord Associations has_oneA has_one association sets up a one-to-one connection with another model, but with different semantics. This association indicates that each instance of a model contains or possesses one instance of another model.

How do I rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.


2 Answers

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.

like image 128
Tim Sullivan Avatar answered Oct 12 '22 05:10

Tim Sullivan


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.

like image 8
cortex Avatar answered Oct 12 '22 07:10

cortex