Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Single Table Inheritance in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 530
    Comment on it

    STI can be considered where single table can be used to represent multiple models based on different type. The parent model inherits from ActiveRecord::Base. Other models inherit from parent model. Data store and accessed from same table for all STI models. Lets take an example of User model which have multiple user types(admin, guest, merchant). In the database schema, sub-models are indicated by a single type column. Adding a type column in a database migration let Rails know that we are planning to implement STI.

    class User < ActiveRecord::Base
    
    end
    
    class Admin < User
    
    end
    
    class Merchant < User
    
    end
    
    class Guest < User
    
    end
    
    

    Query Admin model:

    Admin.where(:status => "active")

    It trigger following SQL code. ActiveRecord automatically fetch data from the users table where the type is admin.

    SELECT "users".* FROM "users" WHERE "users"."type" IN ('admin') AND "users"."status" = 'active'

    STI is useful for all models that save data to the same table and share some functionlaities. Additionally we can write methods in sub classes. STI allows to keep data in a single table while writing specialized functionality.

    Implementation

    Schema of table :

    class User < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.string :type
          t.string :status
          t.string :email
          t.timestamps
        end
      end
    end
    

    After the schema is set up, the next step is to set up models and inheritance.

    STI should be used carefully and only when required. If sub-classes that you want to use for STI have many different data fields, then the field may contain null values. That is not a preferred approach and hard to scale over time. In such cases you may prefer separate models to maintain the tables and functionalities.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: