I am new to rails 4. I have gone through lots of tutorials and trying to solve below scenario. But still no success. Can anybody point me in the right direction. How to handle associations for below scenario.
Scenario:
1. Patient can have many surgeries.
2. Surgery has two types (Patient will undergo only one surgery at a time.)
a.) Surgery Type A (if chosen, record 15 column fields values)
b.) Surgery Type B (if chosen, record 25 column fields values)
3. Surgery Type A can be of any one type.
a.) unilateral (if chosen, record 10 column fields for unilateral & skip bilateral)
b.) bilateral (if chosen, record 10 column fields for bilateral & skip unilateral)
4. Surgery Type B can be of any one type.
a.) unilateral (if chosen, record 10 column fields for unilateral & skip bilateral)
b.) bilateral (if chosen, record 10 column fields for bilateral & skip unilateral)
I need some suggestions to handle associations correctly.. This is little confusing, I need to record lot of field values in table based on each surgery type and sub type (unilateral or bilateral).. What is the best way to handle associations for this scenario and later fetch data easily for reporting purpose.
Thanks in Advance
So, the complex part of your situation is that you have one thing (Surgery) that can be of many different types, and the different types have different fields. There are a number of different approaches to this problem, and I don't believe there's wide consensus on the 'best way'.
The first and simplest way (from a data model perspective, at least), is 'just put it all in one thing' - make a Surgery model, give it a
surgery_type
field to specify which type it is, and give that one record all 45 fields, and then use logic in your views to display only the relevant fields based on thesurgery_type
field, and to validated the presence of only those fields, and so on.A more complex variant on this is Single Table Inheritance, in which you have multiple models, but they all live in the same table.
There are some obvious downsides to this approach - 45 fields is a lot, and when most of them are empty for any given record, that feels wasteful (and can have performance impacts). Which is why the various other patterns exist.
And so, as an alternative, there is Multiple Table Inheritance, which Rails implements via polymorphism. In this pattern, a Patient has_many Surgeries, but this is a polymorphic association, meaning that it can refer to other objects of multiple types. In this pattern, you'd have either two or four models representing types of surgery, and associate each one to a patient. The
UnilateralEndocrineSurgery
model, for instance, only needs its ten fields. The downsides of polymorphism include making it more difficult to work with groups of Surgery objects, because they are of different types and respond to different methods.The relative strengths of these approaches are complex and frequently debated, and enumerating them is beyond the scope of a SO answer.