2012-08-14 36 views
0

我正在使用rails,我有兩個表Post和標籤與habtm關係。不要在HABTM中工作AND條件

的下列句子工作:

@posts = Post.find(:all, :include=>:tags, :conditions => ['tags.term LIKE ? OR tags.term LIKE ?', "%Barcelona%", "%restaurante%" ]) 

@posts = Post.find(:all, :include=>:tags, :conditions => ['tags.term in (?)', ['Barcelona','restaurante'] ]) 

但是這樣一來,與AND條件,不工作:

@posts = Post.find(:all, :include=>:tags, :conditions => ['tags.term LIKE ? AND tags.term LIKE ?', "%Barcelona%", "%restaurante%" ]) 

我想知道這句話獲得所有包含tags.term的帖子:「Barcelona and r estaurante 「

在此先感謝

埃米利奧

+0

你的意思是不工作?它會給出任何錯誤嗎?你確定有行符合這些條件嗎? – RubyDubee 2012-08-14 13:14:34

+0

首先,habtm和條件查找是不推薦使用的方法,您不應該使用它們。 嘗試通過以下方式將HABTM重寫爲顯式has_many和has_many: 您的查詢在某種程度上無效。請發佈Rails錯誤輸出。 – Vladson 2012-08-14 13:23:01

+0

意味着不返回任何值,並有一些包含兩個標籤的行。不要返回任何錯誤。 – emiliojoel 2012-08-14 14:41:04

回答

0

我回應我自己,對我的作品,希望可以幫助別人:

@posts = Post.find_by_sql(」 SELECT * FROM帖子p其中(來自posts_tags的select count(distinct t.id)pt左連接標籤t on pt.tag_id = t.id其中t.term in('Barcelona','restaurante')和pt.post_id = p.id)> = 2 「)