2012-06-26 49 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