I have a model Widgetwith inheritance (I use Single-Table Inheritance, but it is equally valid for a class at the table). Some of the subclasses require a specific field; others do not.
class Widget < ActiveRecord
ALL_WIDGET_TYPES = [FooWidget, BarWidget, BazWidget]
end
class FooWidget < Widget
validates_presence_of :color
end
class BarWidget < Widget
end
class BazWidget < Widget
validates_presence_of :color
end
I am creating a New Widget form ( app/views/widgets/new.html.erb) and would like to dynamically display / hide the box colorbased on <select>for widget_type.
<% form_for @widget do |f| %>
<%= f.select :type, Widget::ALL_WIDGET_TYPES %>
<div class='hiddenUnlessWidgetTypeIsFooOrBaz'>
<%= f.label :color %>
<%= f.text_field :color %>
</div>
<% end %>
I can easily write some jQuery for watching events onChangeon widget_type, but that would mean putting some constant WidgetTypesThatRequireColorin my Javascript. It is easy enough to do this manually, but it will most likely disconnect from the model classes Widget.
Javascript , content_for(:js) yield :js . ?