Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t.belongs_to in migration

I was using Ryan Bates's source code for railscasts #141 in order to create a simple shopping cart. In one of the migrations, he lists

class CreateProducts < ActiveRecord::Migration   def self.up     create_table :products do |t|       t.belongs_to :category       t.string :name       t.decimal :price       t.text :description       t.timestamps     end   end    def self.down     drop_table :products   end end 

Here is the Product model:

class Product < ActiveRecord::Base  belongs_to :category end 

What is the t.belongs_to :category line? Is that an alias for t.integer category_id?

like image 234
Tyler DeWitt Avatar asked Feb 27 '12 19:02

Tyler DeWitt


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.

What does rake db migrate do?

A migration means that you move from the current version to a newer version (as is said in the first answer). Using rake db:migrate you can apply any new changes to your schema. But if you want to rollback to a previous migration you can use rake db:rollback to nullify your new changes if they are incorrectly defined.

How does rails keep track of migrations?

Every time a migration is generated using the rails g migration command, Rails generates the migration file with a unique timestamp. The timestamp is in the format YYYYMMDDHHMMSS . Whenever a migration is run, Rails inserts the migration timestamp into an internal table schema_migrations .

What is a rails migration?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.


2 Answers

The t.belongs_to :category is just a special helper method of rails passing in the association.

If you look in the source code belongs_to is actually an alias of references

like image 66
Justin Herrick Avatar answered Sep 21 '22 21:09

Justin Herrick


$ rails g migration AddUserRefToProducts user:references  

this generates:

class AddUserRefToProducts < ActiveRecord::Migration   def change     add_reference :products, :user, index: true   end end 

http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration

like image 26
shilovk Avatar answered Sep 18 '22 21:09

shilovk