Ronald Fischer
2014-May-21 12:18 UTC
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? -- Posted via http://www.ruby-forum.com/. -- 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 rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/f1511c8936c71770b55467b512d99fd4%40ruby-forum.com. For more options, visit https://groups.google.com/d/optout.