Rails中如何获取子类数组
我有一个模型对象,它是 ActiveRecord 的子类。此外,使用 STI,我定义了该对象的子类,它们定义了不同的类型和行为。结构看起来像这样:
class AppModule < ActiveRecord::Base
belongs_to :app
end
class AppModuleList < AppModule
end
class AppModuleSearch < AppModule
end
class AppModuleThumbs < AppModule
end
现在,在用户可以选择创建新 AppModule 的视图中,我希望他们从下拉菜单中进行选择。但是,我无法使用 subclasses() 方法获取 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>
我将不胜感激。多谢!
I have a model object which subclasses ActiveRecord. Additionally, using STI, I have defined subclasses of this object, which define different types and behaviors. The structure looks something like this:
class AppModule < ActiveRecord::Base
belongs_to :app
end
class AppModuleList < AppModule
end
class AppModuleSearch < AppModule
end
class AppModuleThumbs < AppModule
end
Now, in a view where the user has the option to create new AppModules, I would like them to select from a dropdown menu. However I have not been able to get a list of subclasses of AppModule using the subclasses() method:
<% 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 %>
I get:
NoMethodError: undefined method `subclasses' for #<AppModule:0x1036b76d8>
I'd appreciate any help. Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来好像
subclasses
之类的最近添加(该方法存在于各种类上在不同的时间点,但不断被洗牌和删除;该链接似乎是该方法坚持的最早的点)。如果无法升级到最新版本的 RoR,您可以编写自己的子类
并使用Class#inherited
(这就是 RoR 的descendents_tracker
确实如此)。It looks as though
subclasses
and the like is a recent addition (the method exists on various classes at various points in time, but kept getting shuffled around and removed; that link seems to be the earliest point that the method stuck around). If upgrading to the most recent version of RoR isn't an option, you can write your ownsubclasses
and populate it usingClass#inherited
(which is what RoR'sdescendents_tracker
does).AppModule.descendants.map &:name
就是您要查找的内容。如:AppModule.descendants.map &:name
is what you're looking for. As in: