Saturday, 10 August 2013

Single Table Inheritance in Ror

Hi Folks/Programmers,
                                      I’ve come across many scenarios ,where a Ruby Rails Developer have to use Inheritance(which is a popular OOPS feature), So today i would like you to share some information about single table inheritance.

 With single table inheritance you have a base model which inherits from ActiveRecord::Base, then one or more sub-classes, which inherit from the base model.

Below here is my simple example:-
My Current example is based on Mobile system. We have a single model called ‘Mobile’ and other models such as ‘Samsung’, ‘Apple’, ‘Nokia’ etc., that inherits the property of Mobile model.

so structure come like

Super class

class Mobile < ActiveRecord::Base


Base class

class Nokia < Mobile


while creating table Mobile  you just create a type string column on your votes table, and rails takes care of the rest..

When you do Nokia.create(model: "E7"), this record will be saved in the mobiles table with type = “Nokia”. You can then fetch this row again using Mobile.where(model: 'E7').first and it will return a Firm object.

If you don’t have a type column defined in your table, single-table inheritance won’t be triggered. In that case, it’ll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

No comments:

Post a Comment