Search code examples
ruby-on-railsinheritancemodelsingle-table-inheritance

Convert model in rails (Single Table Inheritance)


Let's say I have two types of users, A and B. Users of type B have fewer privileges and less-strict validations on fields (more can be blank). Otherwise, they're basically the same as type A. This fact makes me inclined to use single table inheritance.

Here's my concern - type B users can upgrade to type A. When they upgrade, they should keep all their associated records. Is there an easy way to convert from one model type to another using STI such that all associations are preserved? Can you give a simple example?


Solution

  • All you need to do is make sure you have given the correct value in type column.

    While upgrading User B to User A, just change the value stored in type attribute to User A's

    class name.

    Eg:

     class Staff < ActiveRecord::Base; end
     class PartTimeStaff < Staff; end
    
     part_time_staff = PartTimeStaff.first
     part_time_staff.type = "Staff"
     part_time_staff.save
    

    it will upgrade the part time staff to staff class.

    All associations should be remain unchanged. Since you only have one actual sql table.

    All the attributes for PartTimeStaff and Staff class are kept in the same table.

    See more details from Rails API and Single Table Inheritance

    thanks