mysql - Rails 范围覆盖选择

标签 mysql ruby-on-rails optimization named-scope

我有一个具有 has_many 关系的模型,以及一个确定它是否有任何子项的范围,例如:

  scope :with_nomination, :include => [:nomination], :conditions => "nominations.service_id IS NOT NULL"

使用它,我可以执行类似 Service.with_nomination 的操作,并接收包含提名子项的所有服务的列表。

问题是,当我执行类似 Service.select("id, firstName, lastName").with_nomination 的操作时,ActiveRecord 本质上执行了一个 SELECT * FROM services非常糟糕,没有利用我煞费苦心建立的索引。

如何重新表述我的查询或修改我的范围以使用 .select() 命令?

最佳答案

原来在我使用的语法中,选择是不可能的,所以它做了一个选择 * 并且任何进一步的选择都已经被覆盖。

我像这样重写了作用域:

scope :no_nomination, joins("LEFT JOIN nominations ON nominations.service_id = services.id").where("nominations.service_id IS NULL")
# important distinction here, the left join allows you to find those records without children

scope :with_nomination, joins(:nomination).where("nominations.service_id IS NOT NULL")

使用这种语法可以让我做一些像 Service.select(:id,:user,:otherfield).with_nomination

关于mysql - Rails 范围覆盖选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10237402/

相关文章:

java - Mapstore 未从数据库 Hazelcast 加载数据

mysql - SQL查询两列有关系

ruby-on-rails - 每个 RAILS_ENV 运行多个 delay_job 实例

ruby-on-rails - spree 更改默认货币和国家

ruby-on-rails - Rails 3、雪人和 SEO

c++ - C++ 中变量作用域的嵌套不正确?

mysql - 从 kubernetes 将 mysql 主机列入白名单

mysql - 连接表上的附加外键

python - Python 的 Deoptim 优化器

php - MySQL 选择没有主 ID 或日期字段的最后插入的记录