在索引视图上按 id 排序的最佳方法

best way to sort by id on the index view

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

我的控制器:

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 排序。

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

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

切勿在任何控制器或模型或任何地方使用 .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