Rails Relationship basics

How to make relationships for rails?

Association

Model Database relationships

No Relationship

@item = Item.find(1)
@category = Category.where(:item_id => @item.id)

Relationship

@item = Item.find(1)
@category = @item.categories

Relationships and Name rule

Relationships are 1:1, 1:n, m:n
To express relationships, we have to follow name rules

  • Foregn key column name is “reftablemodel_id” example (item_id, user_id)
  • If you use middlein table, you use table1_table2 example (authors_books)

Database?
This is not actually foreign key in database.

List

Name Description
belongs_to Access from ref table
has_many Reverse of belong_to, Create 1:n to 1 object
has_one 1:1, or 1:0..1
has_and_belongs_to_many n:m
has_many:through m:n, and cross over model(middlein table)

Let’s see each cases.