Monday, January 2, 2017

Master Many-to-Many Associations with ActiveRecord

Modeling many-to-many relationships between data entities in the ActiveRecord world isn't always a straightforward task. Even if we have a well-defined ER diagram to work with, it's not always clear which ActiveRecord associations we should be using and what the implications of our decision will be. There are two types of many-to-many relationships: transitive and intransitive. In mathematics,

A binary relation R is transitive whenever an element A is related to an element B, and B is in turn related to an element C.

To put this into a data modeling context, a relationship between two entities is transitive if it can be best expressed through the introduction of one or more other entities. So, for instance, it's easy to see that a Buyer buys from many Sellers while a Seller sells to many Buyers. However, the relationship is not fully expressed until we start adding entities such as Product, Payment, Marketplace and so on. Such relationships can be called transitive many-to-many as we rely on the presence of other entities to fully capture the semantics of the relationship. Luckily, ActiveRecord allows us to model such relationships with ease. Let's start by looking at the simplest ActiveRecord many-to-many associations and work our way up.

Continue reading %Master Many-to-Many Associations with ActiveRecord%


by Fred Heath via SitePoint

No comments:

Post a Comment