54

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?

6 Answers 6

74

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

0
21
$ 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

16

Yes, it's an alias; It can also be written t.references category.

1
8

First: the migration

rails generate migration add_user_to_products user:belongs_to

(in this situation) is equivalent to

rails generate migration add_user_to_products user:references

and both create

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

You could 'read' add_reference :products, :user, index: true as "products belong to user(s)"

In the schema, the migration will create a field in the items table called "user_id". This is why the class is called AddUserToProducts. The migration adds the user_id field to products.

Second: the model

He then should have updated the product model as that migration would have only changed the schema. He would have had to update the user model too with something like

class User < ActiveRecord::Base
 has_many :products
end

In general

rails g migration add_[model linking to]_to_[table containing link] [model linking to]:belongs_to

Note: g is short for generate

class User < ActiveRecord::Base
 has_many :[table containing link]
end
4

add_belongs_to(table_name, *agrs) is what you are looking for. You can read about here

1
  • This was the most useful to me. I used it inside a create_table block like this: t.belongs_to :user, null: false, index: { unique: true } I wanted the index, but I needed it to force it to be unique per user
    – curveorzos
    Commented Sep 14, 2022 at 17:07
1

Yes, t.belongs_to :category acts as an alias for t.integer category_id, in that it causes an appropriately typed category_id field to be created.

In MySQL, the migration gets me a table like this (note the category_id field on the second row):

mysql> describe products;
+-------------+---------------+------+-----+---------+----------------+
| Field       | Type          | Null | Key | Default | Extra          |
+-------------+---------------+------+-----+---------+----------------+
| id          | int(11)       | NO   | PRI | NULL    | auto_increment |
| category_id | int(11)       | YES  |     | NULL    |                |
| name        | varchar(255)  | YES  |     | NULL    |                |
| price       | decimal(10,0) | YES  |     | NULL    |                |
| description | text          | YES  |     | NULL    |                |
| created_at  | datetime      | YES  |     | NULL    |                |
| updated_at  | datetime      | YES  |     | NULL    |                |
+-------------+---------------+------+-----+---------+----------------+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.