rails active record 使用default_scope is evil, 記一次 order not work 的排查

  源於一次BUG,有一張表後期添加了 updated_at 時間戳, 而後想要查詢最近一次更新的行的 updated_at, 而後果斷mysql

  MyModel.order('id DESC').where.not(updated_at: nil).limit(1).first.idsql

  查詢最新更新的行, 結果發現不管如何都沒法獲取到正確的數據, 不管是 order('id DESC') 仍是 order('id ASC') 最後得到的數據都是同樣的google

  

  隨機查看mysql產生的語句, spa

  SELECT  `mymodels`.* FROM `words` WHERE (`mymodels`.`updated_at` IS NOT NULL)  ORDER BY txt ASC, id DESC LIMIT 1插件

  不管怎樣查詢語句一直有個 txt ASC, 致使查詢語句沒法正常工做。it

 

  忽然想起久遠前爲了使用分頁插件, 使用了 ActiveRecord 的 default_scope 選項: class

   default_scope { order('txt ASC') }date

  這將致使每次查詢的時候執行  default_scope 中傳入的行爲。 model

 

  default_scope 的使用就是萬惡的根源, 可是之前有很多邏輯實際上依賴了這個特性的使用, 又不能改只能OTL,  不過還好能夠使用 MyModel.unsope 選項來關閉這個特性分頁

  MyModel.unscoped.order('id DESC').where.not(updated_at: nil).limit(1).first.id

  產生出來的 sql 語句終於正常了

 

  又多google了一下, 發現這個特性確實是一個很糟糕的東西:

  TODO 未完待續

相關文章
相關標籤/搜索