Rails在视图中切换案例

我想在我的视图中写一个switch case:

   "one") %>  "two") %>  "three") %>   

但它不起作用。 我是否必须在每行的某处添加 ? 有任何想法吗 ? 谢谢 !

when你进入相同的区块when你应该先拉第一个

 <% @prods.each_with_index do |prod, index|%> <% case index when 0 %><%= image_tag prod.img, :id => "one") %> <% when 1 %><%= image_tag prod.img, :id => "two") %> <% when 2 %><%= image_tag prod.img, :id => "three") %> <% end %> <% end %> 

不要在你的观点中加入太多逻辑。

我会添加一个帮手

 def humanize_number(number) humanized_numbers = {"0" => "zero", "1" => "one"} humanized_numbers[number.to_s] end 

你可以从视图中调用它

 <%= image_tag("#{prod.img}", :id => humanized_number(index)) %> 

首先,您应该考虑将此function抽象为辅助方法,以避免使用逻辑混乱您的视图。

其次,由于erb解析代码的方式,在ERB中使用case语句有点棘手。 请尝试(未经测试,因为此刻我手边没有ruby):

 <% @prods.each_with_index do |prod, index|%> <% case index when 0 %> <%= image_tag("#{prod.img}", :id => "one") %> <% when 1 %> <%= image_tag("#{prod.img}", :id => "two") %> <% when 2 %> <%= image_tag("#{prod.img}", :id => "three") %> <% end %> <% end %> 

有关更多信息,请参阅此主题。

您还可以使用<%- case index -%>语法:

 <% @prods.each_with_index do |prod, index| %> <%- case index -%> <%- when 0 -%><%= image_tag prod.img, :id => "one") %> <%# ... %> <%- end -%> <% end %> 

这对我来说有空白。

  

我认为在再培训局,你必须把条件放在线下。 像这样:

 <% @prods.each_with_index do |prod, index| %> <% case index %> <% when 0 %> <%= image_tag("#{prod}", :id => "one") %> <% when 1 %> <%= image_tag("#{prod}", :id => "two") %> <% when 2 %> <%= image_tag("#{prod}", :id => "three") %> <% end %> <% end %> 

Ruby支持使用then关键字的一行条件的case-whens,但我不认为ERB可以正确解析它们。 例如:

 case index when 0 then "it's 0" when 1 then "it's 1" when 2 then "it's 2" end