0

我有这个循环:

<% @checks.each do |check| %>
  <tr>
    <td><%= check.name %></td>
    <td><%= check.type.name %></td>
    <td><%= check.department.name %></td>
    <td><%= check.due_by %></td>
    <td><span class="label label-success"><%= check.state.name %></span></td>


    <td><%= link_to 'Edit', edit_check_path(check) %></td>
    <td><%= link_to 'Delete', check, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>    

并且取决于什么check.sate.name等于,我需要它有一个不同的类,例如,如果它等于complete,它有这个类"label label-success",如果它incomplete有,"label label-danger"等等。

4

2 回答 2

1

这就是辅助方法的用途。改变

<td><span class="label label-success"><%= check.state.name %></span></td>

类似于

<td><span class="label label-<%= state_label(check.state.name) %>"><%= check.state.name %></span></td>

然后state_label在你的内部定义一个app/helpers/check_helper.rb

def state_label(state)
  case state
    when "complete"
      "success"
    when "incomplete"
      "danger"
    else
      "some-default-state"
end

我更喜欢装饰器/演示者模式,而不是像这样的助手的实现。一个优秀的 gem 是https://github.com/drapergem/draper给定一些State你可以添加一个label_class方法来StateDecorator允许你用一个装饰的来做这样的事情Check

<td><span class="label label-<%= check.state.label_class %>"><%= check.state.name %></span></td>

label_class可能看起来像这样

def label_class
  case model.state
    when "complete"
      "success"
    when "incomplete"
      "danger"
    else
      "some-default-state"
end
于 2013-08-13T13:26:03.500 回答
0

你可以写一个小助手,例如:

def check_state_label(state_name)
  label_class = case state_name
                when "complete"
                  "label label-success"
                when "incomplete"
                  "label label-danger"
                else
                  "label"
                end
  content_tag :span, state_name, class: label_class
end

并这样称呼它:

<td><%= check_state_label(check.state.name) %></td>
于 2013-08-13T13:25:02.760 回答