【问题标题】:Rails - Sort items and change title according to sortingRails - 根据排序对项目进行排序并更改标题
【发布时间】:2021-03-13 14:41:17
【问题描述】:

我有一个table,里面有动物。我只有 2 个species:狗和猫。

我想对视图中的项目进行排序,并在动物物种出现时添加h1(例如:Cats Names、Dogs Names)。我可以通过将狗(@dogs) 和猫(@cats)放入controller 中的不同变量来做到这一点,但如果可能的话,我想在view 中实现它。

我可以在我的视图中对动物进行排序,例如:

 <% @animals.sort_by(&:specy).each do |animal| %>
       // Here I need to add a h1 when species change
      <%= animal[:name] %>
  <% end %>

我想在视图中排序和显示的方式是:

猫名
贝拉
小猫
Lilt
狗名
查理
露娜
马克斯

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5


    【解决方案1】:

    有时使用两个查询会更好,您可能会为自己节省一大段代码,并且会更好,更易于阅读。但是如果你真的想在视图中解决它,你可以这样做:

    在你的控制器中

    # other conditions are omitted
    @animals = Animal.order(:specy)
    

    在视图中

    <% last_specy = nil %>
    <% @animals.each do |animal| %>
      <% if last_specy != animal.specy %>
        <h1><%= animal.specy %> names</h1>
        <% last_specy = animal.specy %>
      <% end %>
    
      <%= animal[:name] %>
    <% end %>
    

    【讨论】:

      【解决方案2】:

      您可以使用group_by 方法根据属性对集合进行分组。

      <% @animals.order(:specy).group_by(&:specy).each do |animal_species, animals| %>
        <h1><%= animal_species %> Names</h1>
        <% animals.each do |animal %>
          <%= animal.name %>
        <% end %>
      <% end %>
      

      来源https://apidock.com/ruby/Enumerable/group_by

      您可能还想使用 sql groupGROUP_CONCAT 函数来获得更好的性能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-22
        • 2022-01-06
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        相关资源
        最近更新 更多