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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With