0

菜鸟需要一些帮助。我正在为我的孩子创建一个家务图表,它应该看起来像一个在线版本:

http://learningandeducationtoys.guidestobuy.com/i-can-do-it-reward-chart

Y 轴上列出的家务和 X 轴上的天数(太阳、星期一...)。盒子让孩子们点击并收到完成家务的星星。

chores/index.html.erb 表是丑陋的代码(对不起):

列出家务

  <table>
    <th><%= "" %></th>
    <th><%= "SUN" %></th>
    <th><%= "MON" %></th>
    <th><%= "TUES" %></th>
    <th><%= "WED" %></th>
    <th><%= "THURS" %></th>
    <th><%= "FRI" %></th>
    <th><%= "SAT" %></th>
    <% @chores.each do |chore| %>
    <tr class="<%= cycle('list-line-odd', 'list-line-even') %>">

    <%     ##TODO.. Fix to be sure to link "post" action to "show" child. %>
    <td>
      <%= image_tag(chore.image_url, :class => 'list-image') %>
      <dt><%=h chore.title %></dt>
    </td>

    <td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
    :remote => true %></td>
    <td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
    :remote => true %></td>
    <td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
    :remote => true %></td>
    <td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
    :remote => true %></td>
    <td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
    :remote => true %></td>
    <td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
    :remote => true %></td>
    <td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
    :remote => true %></td>


  </tr>
  <% end %>
</table>
</div>

以上为每天的每项杂务创建了“添加到钱包”按钮。Wallets 是 Children 和 Chores Tables 之间的连接表。两个问题:

  1. 我如何将按钮切换到表格中的框,单击时会变成星星图像(根据示例)?
  2. 如何重构表中的代码,以免违反 DRY 规则?
4

1 回答 1

2

这里有两个问题,这使得回答起来很尴尬。对于 DRY 部分,您应该认识到您多次复制粘贴相同的语句,这是错误的形式。一般来说,这种事情最好表示为带有单个语句实例的某种循环。

一个例子是将你的日子汇总成一个存储在某处的常量,然后使用它:

<% DAYS.each do |day| %>
<th><%= day_name %></th>
<% end %>

DAYS可以在方便的地方定义,例如在与此相关的模型中,或类似的东西中。MyModel::DAYS如果是这种情况,它可能需要一个前缀,但工作方式相同。

真的不清楚为什么你使用的模式<%= "X" %>每次都会返回相同的字符串X

您还可以使用相同的原理迭代其他七个td元素:

<% DAYS.each do |day| %>
<td class="button"><%= button_to "Add to Wallet", wallets_path(:chore_id => chore, :child_id => session[:child_id]),
:remote => true %></td>
<% end %>

即使day没有使用变量,这里的驱动因素显然是天数,所以它是有道理的。如果你有一个五天的星期,这些列会相应地缩小。

至于您问题的第二部分,您正在寻找的最好表示为这些表格单元格的 jQuery onclick 处理程序。使用不显眼的 JavaScript 技术,您可以很容易地在整个类 DOM 元素上定义一个操作:

$('td.button').live('click', function () { ... });

您将...使用获取和更新单元格的 AJAX 调用来填写该部分。此时单元格内不需要实际的按钮,只需一些 CSS 即可使单元格具有正确的大小和颜色。出于样式原因,这可以通过相应地调整选择器来轻松应用于单元格内的元素。

于 2011-05-11T14:45:16.913 回答