2011-07-15 35 views
1

假設我有一個模型:如何使用Squeel指定此查詢?

class Question < ActiveRecord::Base 
    attr_accessible :title # it has title attribute 
    has_many :pictures 
end 

我想定義一個scope查詢稱爲completed說:

返回所有的問題,即:

  • 標題是不是空 或
  • 至少有1張圖片

我該怎麼做?

到目前爲止,我有:

class Question < ActiveRecord::Base 
    attr_accessible :title # it has title attribute 
    has_many :pictures 

    scope :completed, where{title != ""} # returns all questions with non-empty title 
end 

這會是很好,如果我可以只說:

class Question < ActiveRecord::Base 
    attr_accessible :title # it has title attribute 
    has_many :pictures 

    scope :completed, where{title != "" || pictures.count > 0} 
end 

回答

6

當然你也可以用Squeel做到這一點!這樣寫你的示波器:

scope :completed, joins{pictures.outer}.where{(title != "") | (pictures.id != nil)}.group{id} 

希望我幫了忙。

+0

這個查詢是否會返回所有問題:_either_有1)title **還是** 2)至少有1張圖片?或者這個查詢是否說「返回有標題**和**至少有一張圖片的問題?」 – sivabudh

+0

我正在查找將執行第一個查詢。也就是說,問題要麼有標題,要麼**至少有一張照片。 – sivabudh

+1

對不起,我誤解了這個問題。你需要一個外連接。我現在發佈了正確的squeel :)! – Gerry