开发者

Loop Trick - How to show one attribute if...?

开发者 https://www.devze.com 2023-01-16 22:26 出处:网络
I\'m looking for a function we can use in a loop to do this: <% for rink in @rinks_in_region %> <%= rink.city #Show Only if city (n-1) != n %>

I'm looking for a function we can use in a loop to do this:

<% for rink in @rinks_in_region %>  
    <%= rink.city #Show Only if city (n-1) != n %> 
    <%= link_to_开发者_开发问答rink(rink.name+" Ice Rink",rink) %>
    <br>
<% end -%>

Basically just show the city only if it's different than the previous one.

Make sense? Thanks for your help!

Alextoul


You could use the group_by method on @rinks_in_region to group rinks by city and then use those groupings to display cities and rinks. It returns a hash mapping the thing you are grouping by, city in this case, to the values in the original collection that are in that group. So:

<% @rinks_in_region.group_by(&:city).each_pair do |city, rinks| %>  
  <%= city %> 
  <% rinks.each do |rink| %>
    <%= link_to_rink(rink.name+" Ice Rink",rink) %>
    <br/>
  <% end -%>
<% end -%>


<% prev_city = nil -%>
<% for rink in @rinks_in_region %>
    <%= rink.city if rink.city != prev_city %>
    <% prev_city = rink.city -%>
    <%= link_to_rink(rink.name+" Ice Rink",rink) %>
    <br>
<% end -%>


Not a ruby answer, but introduce a new variable, call it 'temp' or something and set that to the current element in your foreach. That way at the beginning of your loop you have access to last loops element.

temp = ''
    <% for rink in @rinks_in_region %>  
        <%= rink.city #Show Only if city != temp %> 
        <%= link_to_rink(rink.name+" Ice Rink",rink) %>
        <br>

temp = city

    <% end -%>

temp = ''
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号