范围内的find_by触发2个查询

abh*_*9yu 8 activerecord ruby-on-rails ruby-on-rails-4

我正在使用Rails 4.2.3和ruby 2.2.1

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

应用程序/模型/ role.rb

scope :default, -> { find_by(default: true) }
Run Code Online (Sandbox Code Playgroud)

现在我跑的时候

> 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`
=> []
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这会触发2个查询并返回错误的结果.

我尝试使用类方法而不是范围

def self.default
  self.find_by(default: true)
end
Run Code Online (Sandbox Code Playgroud)

现在我跑的时候

Role.default

#this is the output I got

Role Load (0.2ms)  SELECT  `roles`.* FROM `roles` WHERE `roles`.`default` = 1 LIMIT 1
=> nil
Run Code Online (Sandbox Code Playgroud)

使用类方法,find_by正常工作.

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

Fre*_*ung 15

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

你应该只使用返回进一步范围的方法,例如where,limit,order等等.