I am on Rails (1) -- Association

Ruby on Rails is the most popular web framework which base on Ruby programming language. From last week, I started a Rails study on Tealeaf academy. In the week, I read some articles and coded a simple project. These help me understood the rails more clearly.

Before I start the Tealeaf course, I already knew about association but not very clearly. I thought association was to help rails knew the database tables, but now I knew more about it. Association actually make common operations simpler and easier in your code, that's no bussiness of database. For example, in model layer, a post belongs to a user, a user has many posts, this association means that you could use user.posts and post.user in your code, rails knows how to find the items automatically.

Rails supports six types of associations:

  • belongs_to
  • has_one
  • has_many
  • has_many :through
  • has_one :through
  • has_and_belongs_to_many

The pair of belongs_to and has_one is to build an 1:1 association. belongs_to and has_many is to build an 1:M association. If you want to build an M:M asscoiation, use belongs_to and has_many :through. Though has_and_belongs_to_many is also to build the M:M association, but it is not recommended.

We should note that, the foreign_key in the database should be always in the model that contains the belong_to side. e.g. the following association:

class Post < ActiveRecord::Base
 belongs_to :user

class User < ActiveRecord::Base
 has_many :posts

The foreign_key should be in posts tables in database, and it should be user_id. The schema of posts should like follwoing:

create_table "posts", force: true do |t| 
  t.integer  "user_id" 

This is the most basicly part of Rails, and I still had many many things to learn. God bless that I could finish the course, and become a Rails master (I know it is a long long way to reach).

Thanks for reading.