find_by一个范围内被烧成2查询 [英] find_by inside a scope is firing 2 queries

查看:123
本文介绍了find_by一个范围内被烧成2查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Rails 4.2.3和Ruby 2.2.1

I am using Rails 4.2.3 and ruby 2.2.1

我已经写在角色模型范围如下:

I have written a scope in roles model as follows:

应用程序/模型/ role.rb

app/models/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查询并返回错误的结果。

As you can see this fires 2 queries and returns wrong result.

我试着用类的方法,而不是范围

I tried with class method instead of scope

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正常工作。

With class method find_by is working properly.

我不能够理解我在做什么错在这里。任何帮助将是AP preciated。先谢谢了。

I am not able to understand what am I doing wrong here. Any help would be appreciated. Thanks in advance.

推荐答案

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

You shouldn't be using find_by inside a scope - find_by actually executes a database query.

您应该只使用返回进一步范围的方法,例如其中,限制等等。

You should only be using methods that return further scopes, for example where, limit, order and so on.

这篇关于find_by一个范围内被烧成2查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆