Skip to content

Instantly share code, notes, and snippets.

@equivalent
Created August 21, 2012 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save equivalent/3414278 to your computer and use it in GitHub Desktop.
Save equivalent/3414278 to your computer and use it in GitHub Desktop.
dynamically defining STI + fixing Rails STI routing problem
class Option < ActiveRecord::Base
def self.sti_class_names
%w[Alert Foo Bar]
end
#define STIs
sti_class_names.each do |class_name|
new_class = Class.new(Option) do
def self.model_name
Option.model_name
end
end
eval "#{class_name} = new_class"
end
end
# you will end up with
# Option
# Option::Alert
# Option::Foo
# Option::Bar
#
# child classes will have model name set to "Option"
# this will fix Rails routing problem described here
# http://stackoverflow.com/questions/4507149/best-practices-to-handle-routes-for-sti-subclasses-in-rails
# ..only disadvantage is that this affects I18n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment