[英]How do I DRY up business logic between sever-side Ruby and client-side Javascript?
I have a Widget
model with inheritance (I'm using Single-Table Inheritance, but it's equally valid for Class-per-Table). 我有一个带继承的
Widget
模型(我使用的是单表继承,但它同样适用于Class-per-Table)。 Some of the subclasses require a particular 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
# no color field
end
class BazWidget < Widget
validates_presence_of :color
end
I'm building a "New Widget" form ( app/views/widgets/new.html.erb
) and would like to dynamically show/hide the color
field based on a <select>
for widget_type
. 我正在构建一个“New Widget”表单(
app/views/widgets/new.html.erb
),并希望根据widget_type
的<select>
动态显示/隐藏color
字段。
<% 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 to watch for onChange
events on widget_type
, but that would mean putting some sort of WidgetTypesThatRequireColor
constant in my Javascript. 我可以轻松地编写一些jQuery来监视
widget_type
上的onChange
事件,但这意味着在我的Javascript中放置某种WidgetTypesThatRequireColor
常量。 Easy enough to do manually, but it is likely to get disconnected from the Widget
model classes. 手动操作很容易,但很可能与
Widget
模型类断开连接。
I would prefer not to output Javascript directly in my view, though I have considered using content_for(:js)
and have a yield :js
in my template footer. 我宁愿不在我的视图中直接输出Javascript,虽然我已经考虑过使用
content_for(:js)
并且在我的模板页脚中有一个yield :js
。 Any better ideas? 有更好的想法吗?
Here is the html I would generate. 这是我将生成的HTML。 You could generate it from the view or helper in various ways.
您可以通过各种方式从视图或帮助程序生成它。
<select ...>
<option class="widget colored">FooWidget</option>
<option class="widget uncolored">BarWidget</option>
<option class="widget colored">BazWidget</option>
</select>
Then have jQ watch the select and show or hide the div based on the class of the selected option. 然后让jQ观察选择并根据所选选项的类显示或隐藏div。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.