2012-06-26 185 views
2

我正在嘗試將標籤整合到一個網站中,並且一直在路障上幾個小時。在我的索引頁上,我想顯示所有至少包含當前所選標籤的所有文章。我看到Rails 3 many to many query condition並添加訂購和過濾多對多關係

@articles = Article.find_by_sql([ "SELECT * FROM articles p 
JOIN (
    SELECT pt.post_id FROM articles_tags pt 
    JOIN posts p ON p.id = pt.articles_id 
    JOIN tags t ON t.id = pt.tag_id 
    WHERE t.label IN (?) 
    GROUP BY pt.post_id 
    HAVING count(pt.post_id) = ? 
) pt ON p.id = pt.post_id", names_array, names_array.size]) 

,但現在我想包括其時間戳誰創造了它的用戶和訂單了。 它不會讓你有或的find_by_sql

幫助

回答

0

假設筆者的結果依次爲表「創造者」,這個怎麼樣:

@articles = Article.find_by_sql([ "SELECT * FROM articles p 
JOIN (
    SELECT pt.post_id FROM articles_tags pt 
    JOIN posts p ON p.id = pt.articles_id 
    JOIN tags t ON t.id = pt.tag_id 
    JOIN creators c ON c.id = p.creator_id 
    WHERE t.label IN (?) 
    GROUP BY pt.post_id 
    HAVING count(pt.post_id) = ? 
) pt ON p.id = pt.post_id ORDER BY articles.created_at", names_array, names_array.size]) 
+0

這沒有工作。它返回一個空數組。如果我刪除您添加的聯接,則排序工作。我試圖看看sql的正常包含()。order看起來像但它是相同的。orders – Bishop

+0

我最終不得不使用兩個查詢來做到這一點。 – Bishop