如何获得导轨中的一系列子类
-
09-10-2019 - |
题
我有一个模型对象,该对象是ActivereCord。此外,使用STI,我定义了该对象的子类,该子类定义了不同的类型和行为。该结构看起来像这样:
class AppModule < ActiveRecord::Base
belongs_to :app
end
class AppModuleList < AppModule
end
class AppModuleSearch < AppModule
end
class AppModuleThumbs < AppModule
end
现在,在用户可以选择创建新AppModules的视图中,我希望他们从下拉菜单中进行选择。但是,我无法使用子类方法()方法获得AppModule的子类列表:
<% form_for(@app_module) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :type %><br />
<%= f.select(:type, options_from_collection_for_select(@app_module.subclasses().map{ |c| c.to_s }.sort)) %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
我得到:
NoMethodError: undefined method `subclasses' for #<AppModule:0x1036b76d8>
感谢任何帮助。非常感谢!
解决方案
看起来好像 subclasses
就像一个 最近的添加 (该方法存在于各个时间点上的各个班级,但不断被整理和删除;该链接似乎是该方法陷入困境的最早点)。如果升级到最新版本的ROR,您可以编写自己的 subclasses
并使用 Class#inherited
(这就是Ror的 descendents_tracker
做)。
其他提示
AppModule.descendants.map &:name
就是您要寻找的。如:
<% form_for(@app_module) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :type %><br />
<%= f.select(:type, options_from_collection_for_select(AppModule.descendants.map(&:name).sort)) %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
不隶属于 StackOverflow