HABTM查询,返回没有关联的记录

时间:2012-09-13 17:51:23

标签: ruby-on-rails

我有两个表格点和标签之间的HABTM关系。我可以使用以下查询找到具有给定标签集的所有点:

ids = [2, 3, 4, 8]
s = Spot.all(:include => 'tags', :conditions => ["tags.id in (?)", ids])

我如何找到没有标签的所有景点?我知道我可能需要对标签进行计数,但我无法弄清楚如何做到这一点。类似的东西:

s = Spot.all(:include => 'tags', :conditions => "tags.count = 0")

1 个答案:

答案 0 :(得分:7)

您需要左连接并找到spots_tags.spot_id为NULL的那些:

s = Spot.joins('LEFT JOIN spots_tags ON spots.id = spots_tags.spot_id').
         where('spots_tags.spot_id IS NULL').all

您可以使用group by和count来执行此操作,但该查询的构建和理解会稍微复杂一些。