We did it by overriding the association_class
method in a new module and included it using the :extend
option. Also created a integer to string mapping hash to make things easier.
In config/initializers
directory or anywhere you like, create a file and define the hash
INT_OBJECT_TYPE_TO_CLASSNAME = { 0 => "Project", 1 => "Task", 2 => "Timesheet" }
class CommentObjectType < ActiveRecord::Base
module ClassNamesAsInt
def association_class
return INT_OBJECT_TYPE_TO_CLASSNAME[restricted_object_type].constantize
end
end
end
In comments.rb
belongs_to :commentable, :polymorphic => true, :extend => CommentObjectType::ClassNamesAsInt
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…