Rails:有很多通过关联 – 找到AND条件,而不是OR条件

我的ActiveRecord模型中有以下查询方法:

def self.tagged_with( string ) array = string.split(',').map{ |s| s.lstrip } select('distinct photos.*').joins(:tags).where('tags.name' => array ) end 

因此,这将查找从逗号分隔列表中获取标记并转换为数组的所有记录。

目前,这会将记录与任何匹配的标记匹配 – 如何使其在匹配所有标记的位置工作。

IE:如果我现在输入:“blue,red”,那么我将获得所有用蓝色或红色标记的记录。

我想匹配所有用蓝色和红色标记的记录。

建议?

– 编辑 –

我的模型是这样的:

 class Photo  :destroy has_many :tags, :through => :taggings ... def self.tagged_with( string ) array = string.split(',').map{ |s| s.lstrip } select('distinct photos.*').joins(:tags).where('tags.name' => array ) end ... end class Tag  :destroy has_many :photos, :through => :taggings end class Tagging < ActiveRecord::Base belongs_to :photo belongs_to :tag end 

标签有两个属性:ID和Name(字符串)。

这应该工作:

 def self.tagged_with( string ) array = string.split(',').map{ |s| s.lstrip } select('distinct photos.*'). joins(:tags). where('tags.name' => array). group("photos.id"). having("count(*) = #{array.size}") end 

上面将匹配至少有红色和蓝色标签的照片。 这意味着如果照片有红色,蓝色绿色标签,那么这张照片也会匹配。

您可以将select语句更改为以下内容:

 select('distinct photos.*').joins(:tags).where('tags.name = ?', array.join(' OR ')) 

哪个会在where子句中正确创建OR字符串。

伊恩。

大声笑这个解决方案不是一个简单的任务 – 我从SQL的角度考虑它,它是UGLY。 我想其他人必须尝试这个,所以我做了一些搜索,发现这篇文章可以帮助你:

HABTM找到“AND”连接,而不是“OR”