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
post.user in your code, rails knows how to find the items automatically.
Rails supports six types of associations:
- has_many :through
- has_one :through
The pair of
has_one is to build an 1:1 association.
has_many is to build an 1:M association. If you want to build an M:M asscoiation, use
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:
The foreign_key should be in
posts tables in database, and it should be
user_id. The schema of
posts should like follwoing:
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).