On thing you have to over-think very well before you start programming in Ruby on Rails(RoR) is the database design and the relationships between tables. How do I name the tables and fields inside the database and what are the relations between tables. In this blog post I explain some things you have to do in RoR and why you have to do it.
Table names
Every table name in RoR needs to be plural. It sounds weird that RoR is telling you how your table should look like but the philosophy behind it explains a lot. For example we take one single user if you put that user in a table with another user you have a table of users.
The next big question is of course how smart is RoR? The plural of product is products that is simple, but if we take category is RoR smart enough to know that the plural is categories? Well to help you nubyonrails.com made a pluralize tool.
Table relations
RoR is using the active record design pattern and gives you 3 different relationships between tables:
- one-to-one
- one-to-many
- many-to-many
You indicate this relationships by adding declarations to your models:
- has_one
- has_many
- belongs_to
- has_and_belongs_to_many
Under here I made some example tables to make the relations more clear.
one-to-one
Every user can only have one order. In this case you use the has_one relation.
one-to-many
every order has a lot of order_items. In the model file of order_item you get the relation: has_one :order
The model file of orders gets the relation: has_many :order_items
You can see that if the relation is has_many you do the plural name of the table. If the relation is has_one you use the singular name.
many-to-many
Categories can have many products and products can be in many categories. The many-to-many are decelerated in the model of ruby as has_and_belongs_to_many.
I hope this post will help a little bit if you start a RoR project
Thank you this help clear up a lot for me.