Rails `.order desc` 在生产环境中不起作用。

huangapple go评论47阅读模式
英文:

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

    &lt;% @address.address.cases.order(due_date: :desc).where.not(invoice_file_name: nil).last(10).each do |d|  %&gt; 
    
            &lt;ul id=&quot;inv&quot;&gt;&lt;p&gt;&lt;%= link_to d.invoice.url do %&gt;
             &lt;li&gt; &lt;%= d.pt_first_name.capitalize %&gt; &lt;%= d.pt_last_name.capitalize %&gt;&lt;/li&gt;
            &lt;% end %&gt;&lt;/p&gt;&lt;/ul&gt;
          &lt;% end %&gt;



</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

huangapple
  • 本文由 发表于 2023年6月8日 15:30:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定