If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is Patron, you’d set things up this way:
1 2 3
The most common relationship used when creating relational databases. A row in a table in a database can be associated with one or (likely) more rows in another table. An example of a one-to-many relationship is a single order has many items on that order. And since relationships work both ways it is not uncommon to hear reference to many-to-one-relationships as well.
- most common kind e.g.
A row in a table is associated to one and only one row in another table. An example of a one-to-one relationship is a person can have one social security number and a social security number can only be assigned to one person.
- In most cases there is no need for a one-to-one relationship as the contents of the two tables can be combined into one table.
When one or more rows in a table are associated with one or more rows in another table. An example of a many-to-many relationship is a table of customers can purchase many products and many customers can purchase a product.
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
1 2 3 4 5
With this setup, you can retrieve @employee.subordinates and @employee.manager
There is another rails cast on self-referential-association. Ryan Bates is amazing.