简体   繁体   中英

Separate “each” to “types” in Rails view

In a State, we have Shops, with database column type in each shop entry: Grocery , Fashion and Food .

I have the following code:

<% @country.states.each_with_index do |state, i| %>
  State <strong><%= i + 1 %></strong>

  <% state.shops.each do |shop| %>
    =====showing attributes of each shop=====
  <% end %>
<% end %>

In the code above, all shops will be listed according to IDs ascending:

Shop ID1 (Type = Food)
Shop ID2 (Type = Fashion)
Shop ID3 (Type = Grocery)
Shop ID4 (Type = Fashion)
Shop ID5 (Type = Food)

Instead of outputting each , I would like to show in the preferred type order:

Fashion
Shop ID2
Shop ID4

Grocery
Shop ID3

Food
Shop ID1
Shop ID5

I tried to use the if state.shops.type == 'Fashion' statement, but doesn't work. What is the proper way to write this?

Thanks.

Use the group_by method:

 <% @country.states.each_with_index do |state, i| %>
   State <strong><%= i + 1 %></strong>

   <% state.shops.group_by(&:type) do |type, shops| %>
     <h3><%= type %></h3>
     <% shops.each do |shop| %>
       =====showing attributes of each shop=====
     <% end %>
   <% end %>
<% end %>

Following the earlier comments there doesn't seem to be any logic to the order that you want. So either you should implement an order attribute like an integer which you can use to sort by in the query. Otherwise you will have to create a block which will do static checks and do custom sorting, perhaps something like this:

@custom_order = {"Fashion" => 0, "Grocery" => 1, "Food" => 2}

<% state.shops.group_by(&:type).sort { |a, b|
  @custom_order[a.first] <=> @custom_order[b.first]
} do |type, shops| %>

As you see, it gets a little messy so I would probably add an order attribute as I mentioned and then do like wuputah said but change to

state.shops(:order => "order ASC").group_by(&:type)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM