我的ActiveRecord模型中有以下查询方法:
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
select('distinct photos.*').joins(:tags).where('tags.name' => array )
end因此,这将查找具有从逗号分隔列表中获取并转换为数组的标记的所有记录。
目前,它匹配具有任何匹配标记的记录--如何使它在匹配所有标记的情况下工作。
例如:如果我当前输入:" blue,red“,那么我得到的所有记录都被标记为蓝色或红色。
我要匹配所有标记为蓝色和红色的记录。
有什么建议吗?
-编辑--
我的模型是这样的:
class Photo < ActiveRecord::Base
...
has_many :taggings, :dependent => :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 < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :photos, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :photo
belongs_to :tag
end标签有两个属性: ID和Name (字符串)。
发布于 2011-05-03 05:06:04
这应该是可行的:
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上面将匹配至少有红色和蓝色标签的照片。因此,这意味着如果一张照片有红色、蓝色和绿色标签,那张照片也会匹配。
发布于 2011-04-30 02:25:12
您可以将select语句更改为以下内容:
select('distinct photos.*').joins(:tags).where('tags.name = ?', array.join(' OR '))这将在where子句中正确地创建OR字符串。
伊恩。
发布于 2011-04-30 09:24:16
LOL这个问题的解决方案不是一项简单的任务--我从SQL的角度考虑了一下,结果很难看。我想一定是别人试过了,所以我做了一些搜索,找到了这篇应该对你有帮助的帖子:
https://stackoverflow.com/questions/5835696
复制相似问题