On Wed, May 21, 2014 at 7:18 AM, Ronald Fischer <[email protected]> wrote: > 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?
As much as I hate to say is, this *might* be a case for single table inheritance... -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAHUC_t_oFnFxTCvZi_EHwg%3DkUpd0-HL9t9tsNbD8nUk5B%2BJJrg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.

