我有一个具有 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/