2015-07-09 25 views
5

我使用2.2.1find_by一個範圍內被燒成2查詢

我在角色模型編寫的一個範圍如下的Rails 4.2.3和Ruby:

應用程序/模型/ role.rb

scope :default, -> { find_by(default: true) } 

現在,當我運行

> Role.default 

#this is the output I got. 

Role Load (0.1ms) SELECT `roles`.* FROM `roles` WHERE `roles`.`default` = 1 LIMIT 1 
Role Load (0.1ms) SELECT `roles`.* FROM `roles` 
=> [] 

正如你可以看到這個觸發2個查詢並返回錯誤的結果。

我用類方法而不是範圍

def self.default 
    self.find_by(default: true) 
end 

試過現在,當我運行

Role.default 

#this is the output I got 

Role Load (0.2ms) SELECT `roles`.* FROM `roles` WHERE `roles`.`default` = 1 LIMIT 1 
=> nil 

用類方法find_by工作正常。

我無法理解我在這裏做錯了什麼。任何幫助,將不勝感激。提前致謝。

回答

7

您不應在範圍內使用find_by - find_by實際上會執行數據庫查詢。

您應該只使用返回更多範圍的方法,例如wherelimitorder等等。