范围内的find_by正在触发2个查询

我正在使用Rails 4.2.3和ruby 2.2.1

我在角色模型中写了一个范围如下:

应用程序/模型/ 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正常工作。

我无法理解我在这里做错了什么。 任何帮助,将不胜感激。 提前致谢。

您不应该在范围内使用find_byfind_by实际上执行数据库查询。

您应该只使用返回其他范围的方法,例如wherelimitorder等。

ActiveRecord是Rails中内置的对象关系映射系统,它为您提供了一组在作用域中使用的方法来抽象出数据库查询。 这些方法列在这里:

http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database

在您的情况下,您将要使用where查询。

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