Answer the question
In order to leave comments, you need to log in
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?
Answer the question
In order to leave comments, you need to log in
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
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.
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 questionAsk a Question
731 491 924 answers to any question