2012-04-19 93 views
1

我有一個的has_many關係的模型和範圍,以確定它是否有任何子女,如:Rails的範圍覆蓋選擇

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

利用這一點,我可以這樣做Service.with_nomination和接收提名兒童的所有服務清單。

問題是,當我做一些像Service.select("id, firstName, lastName").with_nomination這樣的活動記錄在本質上是一個SELECT * FROM services這是非常糟糕的,並沒有利用我辛辛苦苦設置的索引。

我該如何重新修改我的查詢或修改我的範圍以使用.select()命令?

+1

我在這方面的專家,並會按照別人附和一個真正的答案,但我認爲你需要做一個加入或lambda與你的範圍之前,你可以用你想要的方式選擇。我已經看到它在源代碼之前完成了我在github上討論過,但還沒有實現這個。當你等待更好的答覆時,只是一個念頭。 – saneshark 2012-04-19 22:18:48

回答

0

原來我在使用的語法中,select是不可能的,所以它執行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