Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何通过在rails的index.html.erb中创建的而不是更新的来显示数据顺序?_Ruby On Rails_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 如何通过在rails的index.html.erb中创建的而不是更新的来显示数据顺序?

Ruby on rails 如何通过在rails的index.html.erb中创建的而不是更新的来显示数据顺序?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有点难为情,因为我无法弄清楚这一点,但index.html.erb显示了一些数据顺序,按更新的位置按顺序排列,正如我想按创建的位置按顺序排列一样,最新的位置在顶部。我该怎么做 我的index.html.erb是标准的 <% @products do |product| %> <%= product.name %> <%= link_to 'Edit', edit_product_path(@product) %> <% end %> 将

我有点难为情,因为我无法弄清楚这一点,但index.html.erb显示了一些数据顺序,按更新的位置按顺序排列,正如我想按创建的位置按顺序排列一样,最新的位置在顶部。我该怎么做

我的index.html.erb是标准的

<% @products do |product| %>
  <%= product.name %>
  <%= link_to 'Edit', edit_product_path(@product) %>
<% end %>

将其写入控制器中

@products=@products.sort_by{| obj | obj.created_at}。反向


我想这应该能解决你的问题。

把这个写在你的控制器上

@products=@products.sort_by{| obj | obj.created_at}。反向


我认为这应该可以解决您的问题。

根据您如何定义@products,您也可以使用order,如:

Product.order('created_at DESC')
这将显示所有产品,并按创建的位置按降序排序

但是,如果使用Product.all.order('created_at DESC'),它将不起作用,因为.all将结果转换为数组。在这种情况下,您需要使用sort_by,正如另一个答案所建议的那样


订单将在您的模型中工作,只要您不在阵列上使用它

根据您定义@products的方式,您还可以使用order,如:

Product.order('created_at DESC')
这将显示所有产品,并按创建的位置按降序排序

但是,如果使用Product.all.order('created_at DESC'),它将不起作用,因为.all将结果转换为数组。在这种情况下,您需要使用sort_by,正如另一个答案所建议的那样


订单将在您的模型中工作,只要您不在阵列上使用它

我可以在模型级别也这样做吗?这有什么区别吗?可能必须是
@products.all.sort\u by
。。。因为.all将允许您调用可枚举函数“sort by”。不过,我还是建议通过数据库来实现这一点,因为这就是数据库的用途。我完全同意@AaronCronincan的观点,我也在模型级实现了吗?这有什么区别吗?可能必须是
@products.all.sort\u by
。。。因为.all将允许您调用可枚举函数“sort by”。然而,我仍然建议通过DB来实现这一点,因为这是数据库的用途。我完全同意@aaroncronif的观点,如果可能的话,这比使用Ruby对返回的记录数组进行排序更可取(效率更高)。我有@products=current\u user.products,所以我猜@products=current\u user.products.order('created\u at DESC'))应该可以工作,对吗?是的,ActiveRecord将正确地结合作用域和排序。如果可能的话,这比使用Ruby对返回的记录数组进行排序更可取(效率更高)。我有@products=current\u user.products,所以我想@products=current\u user.products.order('created\u at DESC')应该可以工作,对吗,ActiveRecord将正确组合范围和顺序。