On Apr 20, 2006, at 05:16 PM, John T. wrote:
Hi all. Got a stupid-simple question about associations. I have two
models - school and course. There are a fixed number of schools (set
up in the migration). Each course is assigned a school and a school
will be associated with multiple courses…
How do I set up the associations? Do (can) I have School :has_one
:course and Course :has_many :schools?
If “a school will be associated with multiple courses”, then School
has_many: courses, which means Course belongs_to :school. The fact
that there are a fixed number of schools is actually irrelevant to
how the two tables of data relate to each other. You only use has_one
when a row from table a is related to one, and only one, row from
table b. That’s not what you’ve described here.
Does the schools table then get a course_id field or the other way
Again, if a “course is assigned a [to a] school”, then the courses
table has a shool_id field. This is also specified by the association.
I don’t think I should have course :belongs_to School, as there will
only be one instance of a school in the Schools table.
Honestly, I’ve never thought about which model I “wanted” to have the
belongs_to association defined in. That was always done naturally by
the nature of the relation. Obviously, in a 1-to-1 relation, it’s
possible to swap the has_one and belongs_to, but I would say that
which ever model you expect to refer to, most often, gets the
has_one, and the not-most-often model gets the belongs_to.