【问题标题】:best way to sort by id on the index view在索引视图上按 id 排序的最佳方法
【发布时间】:2021-03-06 17:06:31
【问题描述】:

我有一个 gossip 控制器和模型,在我用这种方式在索引视图中显示我所有的 gossip 之前:

我的控制器:

def index
  @gossips = Gossip.all
end

我的观点 index.html.erb :

<% @gossips.each do | gossip | %>
  <div class="card gossip-card" style="width: 18rem;">
    <div class="card-body">
      <h5 class="card-title"><%= gossip.title %></h5>
      <h6 class="card-subtitle mb-2 text-muted"><%= gossip.user.username %></h6>
      <%= link_to "Read", gossip_path(gossip), :class => "btn btn-info" %>
      <%= link_to "Edit", edit_gossip_path(gossip), :class => "btn btn-success" %>
      <%= link_to "Delete", gossip_path(gossip), :class => "btn btn-danger", method: :delete, data: { confirm: "Are you sure?"} %>
    </div>
  </div>
<% end %>

但是当我编辑一个八卦时,它一直到最后一个位置,可能是因为它们是按修改日期排序的。 所以我为我的控制器找到了这个解决方案:

def index
  @gossips = Gossip.all.sort_by { |gossip| gossip.id  }
end

我想知道我的八卦通常按修改日期排序是否正常,是否有可能比我做的更干净地按 id 排序。

【问题讨论】:

    标签: ruby-on-rails sorting view controller


    【解决方案1】:

    您可能希望对数据库进行排序:

    def index
      @gossips = Gossip.order(:id)
    end
    

    【讨论】:

      【解决方案2】:

      永远不要在任何控制器或模型或任何地方使用.all。适合您的用例

      # for ascending order
      def index
        @gossips = Gossip.order(:id)
      end
      
      # for descending order
      def index
        @gossips = Gossip.order(created_at: :desc)
      end
      

      同时尝试参考 Rails 文档以供参考。

      https://guides.rubyonrails.org/active_record_basics.html#read

      【讨论】:

      • “永远不要使用.all” - 你能详细说明一下吗?
      • 为什么从不使用 .all ?
      • 在一个请求中列出所有数据不是一个好方法(假设它不是一组恒定的数据,而是定期增加),因为它会增加响应时间。使用分页总是更好,还可以添加缓存以缩短响应时间。
      • 多么夸张。 “.all 不适合所有可能的用例”和“从不使用 .all”之间有很大的区别。此外,这个答案重复了已经存在的答案。
      • @inmydelorean 非常感谢您的启发:D,从技术上讲,它不是重复的。
      猜你喜欢
      • 2012-09-23
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      相关资源
      最近更新 更多