我有点尴尬,我无法弄清楚这一点,但 index.html.erb 显示了 updated_at 的一些数据顺序,因为我想通过 created_at 对它进行排序,最新的在顶部。我怎样才能做到这一点 ?
我的 index.html.erb 是标准的
<% @products do |product| %>
<%= product.name %>
<%= link_to 'Edit', edit_product_path(@product) %>
<% end %>
我有点尴尬,我无法弄清楚这一点,但 index.html.erb 显示了 updated_at 的一些数据顺序,因为我想通过 created_at 对它进行排序,最新的在顶部。我怎样才能做到这一点 ?
我的 index.html.erb 是标准的
<% @products do |product| %>
<%= product.name %>
<%= link_to 'Edit', edit_product_path(@product) %>
<% end %>
根据您定义@products 的方式,您还可以使用 order,如下所示:
Product.order('created_at DESC')
这将显示所有产品并按 created_at 降序排序。
但是,例如,如果您使用 Product.all.order('created_at DESC'),它将不起作用,因为 .all 会将结果转换为数组。在这种情况下,您需要使用 sort_by,正如另一个答案所建议的那样。
只要您不在阵列上使用订单,订单就可以在您的模型中使用。
把它写在你的控制器中
@products = @products.sort_by {|obj| obj.created_at }.reverse
我认为这应该可以解决您的问题。