Single Table Inheritance and 'type' value for namespaced classes
Asked Answered
B

2

10

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?

Behan answered 3/11, 2014 at 7:33 Comment(3)
Did u tried aliasing the class name. something like this. Guest = Reservation::Guest, I don't think its best to change the type at runtime, as there might be many dependent things.Perspire
@AbibullahRahamathulah many things break by aliasing. So that would not be the solution.Behan
@AmitPatel is this what you need?Crossroad
C
28

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
Crossroad answered 11/11, 2014 at 17:14 Comment(0)
E
18

I know it's an old question, but maybe someone will use it.

Expanding on the answer by mohameddiaa27, the easiest way to get rid of namespace is to declare store_full_sti_class, since it's used by sti_name.

class Reservation

  # don't include namespace in type column
  def self.store_full_sti_class
    false
  end
end
Edrei answered 23/9, 2015 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.