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!
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 own subclasses
and populate it using Class#inherited
(which is what RoR's descendents_tracker
does).
AppModule.descendants.map &:name
is what you're looking for. As in:
<% 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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With