(Click here for a brief overview on using Activerecord models.)
Relational Design
The simplest relational design for such a situation can be boiled down to the chart below:
A sample schema to handle many-to-many self joins. |
In this example, any user can be a vendor to many customers, and any user can be a customer to many vendors. You need to make a distinction between the types of users, but how? And how would I select only certain relationships based on other properties?
Defining the Models
The model definition will use a has many through (HMT) association. As a side note, I won't discuss this comparison in detail since it's beyond the scope of this post, but HMT is very similar to has-and-belongs-to-many (HABTM), and both allow for many-to-many relationships. That said, HMT was chosen because it allows for the developer to work with any additional properties in the association data (in this case, the Relationship model).
User model definition |
For this case, we will not want to always directly access our users collection; we may want to use users in context. The User model has been set up so it can be accessed through use of aliases. I'll illustrate later how you can access a user's customers and vendors from within the User controller or an external Ruby script executed using Rails runner.
Relationship model definition |
The Relationship model provides the ability to define the relationship between the two classes of Users.
Accessing the Model data
All the scaffolding in the Models definitions leads to ease of use for the developer.
|
|
In my next post, I'll show how to expose this data in a RESTful API endpoint.
No comments:
Post a Comment