Getting your head around relationships - Has_many and belongs_to
This used to confuse the life out of me.
Question: What does it mean if I should say that a classroom has_many students? Answer: • (It implicitly means that a student belongs_to a classroom) • It means that a student row will have a column name with class_id as a foreign key (assuming we are using rails conventions of course).
Question: What does it mean if I should say that: sheep belongs_to a farmer? Answer It means that there is a foreign key in the sheeps table which refers to the farmers table. E.g. farmer_id. But we do not know, based on that statement alone, whether a farmer has_many sheep, or only has one etc.
Summary: • If a parent has many children, and every child belong to a parent, then: (i) the child record will have a parent_id foreign key and (ii) many children can have the same value in their parent_id column.
I hope that makes sense!
Assumed Knowledge: • Primary and foreign keys. • The concept of a table (rows and columns) in a database.