Please help modelling "has-a-vector-of-3" relationship

In my application, I have 3 models. Let’s call them X, Y and Z for
brevity. Their relationship are as follows:

  • One X has an arbitrary number (maybe zero) items of type Y.

  • One Y has 2 or 3 items of type Z. Moreover, these items are ordered,
    i.e. I need to record somehow, which is the first one, which the second
    etc.

  • From a certain Z, I need to find out which Y it belongs to, and from a
    Y, I need to find out which X it belongs to.

  • When an X is deleted, the contained Y need to be destroyed too.

  • When an Y is deleted, the contained Z need to be destroyed too.

Here is what I have so far:

The mapping between X and Y is straightforward. When generating the
model for Y, I included a field X:references. Within X.db, I included a

has_many: :y, dependent: :destroy

For the mapping between Y and Z, I didn’t come up with a convincing
solution. When generating the model Z, I included a field Y:references,
but how do I model the 2 or 3 Z entities within Z?

From a database viewpoint, I would need three fields (with different
names, say z1, z2 and z3), which all contain the ID of a certain row
within z. The field z3 might be NULL (in SQL terms), while z1 and z2
must always be provided.

But how do I define this in the “ruby generate model” command? The only
field type which could store a reference to another table, would be
‘references’, but don’t see how this would help me in this case.

I already thought about this workaround: I do a has_many relationship
from Y to Z, and my application makes sure, that there are only 2 or 3 Z
elements assigned at one time. In addition, I add to my Z table a field,
which says whether it is number one, two or three within this group.

This should work, but can this really be called an elegant design?

On Wed, May 21, 2014 at 7:18 AM, Ronald F. [email protected]
wrote:

Y, I need to find out which X it belongs to.
has_many: :y, dependent: :destroy
But how do I define this in the “ruby generate model” command? The only
field type which could store a reference to another table, would be
‘references’, but don’t see how this would help me in this case.

I already thought about this workaround: I do a has_many relationship
from Y to Z, and my application makes sure, that there are only 2 or 3 Z
elements assigned at one time. In addition, I add to my Z table a field,
which says whether it is number one, two or three within this group.

This should work, but can this really be called an elegant design?

As much as I hate to say is, this might be a case for single table
inheritance…

tamouse m. wrote in post #1146720:

As much as I hate to say is, this might be a case for single table
inheritance…

So be it! :wink:

Thank you for the confirmation.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs