我有这个循环:
<% @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"
等。
答案 0 :(得分: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
我更喜欢装饰器/演示器模式而不是像这样的助手的实现。一个很棒的宝石是https://github.com/drapergem/draper给定一些State
,您可以向label_class
添加StateDecorator
方法,这样您就可以使用装饰Check
来执行此类操作1 p>
<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
答案 1 :(得分: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>