A
A
Alexey2012-07-28 16:47:41
Ruby on Rails
Alexey, 2012-07-28 16:47:41

Is there any way to organize polymorphism in ActiveRecord without the type field?

Actually, the task is to pull an application on RoR onto a long-existing base (whose structure it is highly desirable not to change). But in this database there are entities with which it would be nice to work through STI. Here a problem arises, because the type field is required to define the class to be created, but it can't be used in the classic way. However, the table has a type_id field that points to a type lookup table. Whether actually probably somehow to implement creation of the necessary classes through the given field/table?
PCt2xDFqE4y5UzKAJSQ.jpg

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey, 2012-07-29
@fuCtor

Implemented the first option (method overloading), did not have to overload much (only two methods). The result of the research was uploaded to github github.com/fuCtor/ext_sti

S
sl_bug, 2012-07-28
@sl_bug

The simplest crutch - see the rails code. Look for how it refers to the type field. Override this method at home. Your method pulls the ClassType and returns name.
The best way is to write a migration that still makes the type field and enters the necessary data there. “It is highly desirable not to change” can always be changed without loss of functionality.

S
sdevalex, 2012-07-28
@sdevalex

Something like ... If the class does not have such a property, then we look in another table ... if we find it, we return it.

class Item < ActiveRecord::Base
  belongs_to :type

  def method_missing(name, *args)
     return type.attributes[name] if type.attributes.has_key? name
     super name, args
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question