Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Table Inheritance and 'type' value for namespaced classes

While working on Rails 2.3.18 to Rails 3.2.x migration I am facing name issue in type column

Here is the relation that is defined.

app/models/reservation.rb

class Reservation
end

class Reservation::Guest < Reservation
end

class Reservation::Event < Reservation
end

While saving Reservation::Guest Or Reservation::Event instance, the type value being saved is Reservation::Guest and Reservation::Event in Rails 3. But in Rails 2 it saves without namespace i.e., Guest or Event.

It requires lots of efforts to migrate existing data and change all the places which expects type without namespace.

Would it be possible to save type without namespace and rest work without making lots of modification across the application?

like image 926
Amit Patel Avatar asked Nov 03 '14 07:11

Amit Patel


People also ask

How does the single-table inheritance work?

In Single-Table Inheritance (STI), many subclasses inherit from one superclass with all the data in the same table in the database. The superclass has a “type” column to determine which subclass an object belongs to. In a polymorphic association, one model “belongs to” several other models using a single association.

What is single-table inheritance in rails?

Single-table inheritance (STI) is the practice of storing multiple types of values in the same table, where each record includes a field indicating its type, and the table includes a column for every field of all the types it stores.

What is a standard prerequisite for implementing single-table inheritance?

To get started with STI from a database perspective, all you need to do is add a field called “type” to the table. Rails takes this type field and applies the name of the sub-classes that inherit from the class for which the table is named as the value for a row of data.


1 Answers

Take a look at sti_name and find_sti_class. (The methods responsible for setting and getting the sti_name)


You can customize them as follows:

class Reservation
  def self.find_sti_class(type_name)
    type_name = self.name
    super
  end
end

class Reservation::Guest < Reservation
  def self.sti_name
    "Guest"
  end
end

class Reservation::Event < Reservation
  def self.sti_name
    "Event"
  end
end
like image 176
mohameddiaa27 Avatar answered Oct 27 '22 00:10

mohameddiaa27