2010-08-21 54 views
0

我有一個標籤對象(id,name)和一個標籤對象(id,tag_id,type)。我想找到所有標籤名稱都是「kevin」的標籤,並且我可以找到一個類型設置爲「people」(類型可以設置爲人物或其他標籤)的外部標籤對象。有沒有更好的SQL方法來完成Ruby的Array.delete_if與Rails.find請求?

我試圖在Rails Tag.find方法的複雜SQL請求,但沒走多遠,所以我現在有兩行試圖使用Ruby的delete_if方法:

people = Tag.find(:all, :conditions => ["name like ?", "Kevin%"]) 
people.delete_if { |p| Tagging.find(:all, :conditions => { :tag_id => p.id, :type => "people" }).empty? } 

它的實際工作,但是必須有一種更智能的方式直接將數據寫入數據庫,對吧?

感謝您的幫助,

凱文

回答

1

試試這個:

Tag.all(:joins => :taggings, :group => :id, 
     :conditions => ["tags.name LIKE ? AND taggings.type = ?", 
         "Kevin%", "person"] 
) 

返回以凱文用於type = 「人」 的標籤。

注:需要group選項以消除重複項。

1

有幾個方面,這可以改善。

最簡單的改進是做一個「SELECT count(*)」而不是加載這些標籤的ActiveRecords。

people = Tag.all(:conditions => ["name LIKE ?", "Kevin%"]) 
people.delete_if { |p| Tagging.count(:conditions => { :tag_id => p.id, :type => "people" }) > 0 } 

但是這件事也可以在SQL完成了一個子查詢:

people = Tag.all(:conditions => [ 
    "name LIKE ? AND id IN (SELECT tag_id FROM people WHERE type=?)", 
    "Kevin%", 
    "people", 
]) 
相關問題