我正在使用标准 STI,并希望在其选项都是父类的子类型的表单上创建一个输入选择。所以我希望 Parent.select_options 返回 ['Child1','Child2','Child3']
class Parent < ActiveRecord::Base
# kinda what I'd like except the descendants method is undefined in rails 2.3
def self.select_options
descendants.map{ |c| c.to_s }.sort
end
end
class Child1 < Parent
end
class Child2 < Parent
end
class Child3 < Parent
end
视图.html.haml
= f.input :parent_id, :as => :select, :collection => Parent.select_options, :prompt => true
更新
感谢@nash 和@jdeseno 只需要使用@jdeseno 方法添加以下初始化程序:
%w[parent child1 child2 child3].each do |c|
require_dependency File.join("app","models","#{c}.rb")
end