英文:
rails .order desc not working in production
问题
以下是翻译好的部分:
"在本地工作正常,但当我将其推送到Heroku时,订单的顺序不正确显示。
<% @address.address.cases.order(due_date: :desc).where.not(invoice_file_name: nil).last(10).each do |d| %>
<ul id=\"inv\"><p><%= link_to d.invoice.url do %>
<li> <%= d.pt_first_name.capitalize %> <%= d.pt_last_name.capitalize %></li>
<% end %></p></ul>
<% end %>
```"
<details>
<summary>英文:</summary>
It is very wierd that the order is working in local but when i push it to heroku its not displaying the correct order
<% @address.address.cases.order(due_date: :desc).where.not(invoice_file_name: nil).last(10).each do |d| %>
<ul id="inv"><p><%= link_to d.invoice.url do %>
<li> <%= d.pt_first_name.capitalize %> <%= d.pt_last_name.capitalize %></li>
<% end %></p></ul>
<% end %>
</details>
# 答案1
**得分**: 2
我猜想原因是`last`方法强制使用升序排序。查看您的日志,您应该会看到类似的内容:
```sql
ORDER BY `cases`.`due_date` ASC LIMIT 10
为了解决这个问题,我会使用limit
方法:
@address.address.cases.order(due_date: :desc).where.not(invoice_file_name: nil).limit(10)
它使用了正确的排序方式:
ORDER BY `cases`.`due_date` DESC LIMIT 10
英文:
I suppose the reason is the last
method is forces the ascending order. Take a look at your logs. You should see something similar:
ORDER BY `cases`.`due_date` ASC LIMIT 10
To fix this I'd use the limit
method:
@address.address.cases.order(due_date: :desc).where.not(invoice_file_name: nil).limit(10)
It uses the proper order:
ORDER BY `cases`.`due_date` DESC LIMIT 10
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论