I have two tables. They are Service Desk and Incident.
I have to relate one of my service desk records with one or more
service
desk record(s) and/or one or more incident record(s). Hence the result
of
my search will both service desk records and/or incident records.
MY PROBLEM IS WHAT SHOULD BE THE TABLE STRUCTURE TO STORE THIS RESULT
INCLUDING THE TYPE OF IT(ie WHETHER IT IS SERVICE DESK OR INCIDENT
RECORD)
One, you can do just as you say and "include the type". Create a
'type' column in each table with either an integer or you can place a
string of "Service Desk" or "Incident"
Also what i would do is, I am positive you have a record or ticket
number or something like that. I would place a 'SD' or 'IN' in front
of the number to so you can tell what kind of record it is. If you
have the same columns in each table then you can combine all the
records in one table and just have a Ticket or Record table.
Use a polymorphic association. It's polymorphic in the sense that it
can associate to any other object in the system. You accomplish this
by adding a compound foreign key -- one column gives the name of the
class and the other gives the id of the instance. Your models would
look something like this:
class ServiceDesk
has_many :serviceables, :polymorphic=>true
belongs_to :service_desk, :as=>:serviceable
...
end
class Incident
belongs_to :service_desk, :as=>:serviceable
...
end
With that...
@service_desk = ServiceDesk.find(1)
@service_desk.serviceables <= a collection of ServiceDesk and
Incident objects (actually a proxy...)
That's essentially what the polymorphic does for you, with the bonus
that "rails magic" takes care of all the coding for you. You only
have to change "related_record_model" to "related_record_type" and
your work is done.
By the way, you don't need a method to render out the name of the
class. Use class.name