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:如果当前如果我输入:“蓝色,红色”,那么我会得到带有蓝色或红色标记的所有记录。
我想匹配所有标记为蓝色和红色的记录。
建议?
-- 编辑 --
我的模型是这样的:
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 和名称(字符串)。
I have the following query method in my ActiveRecord model:
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
select('distinct photos.*').joins(:tags).where('tags.name' => array )
end
So, this finds all records that have tags taken from a comma separated list and converted into an array.
Currently this matches records with ANY matching tags -- how can I make it work where it matches ALL tags.
IE: if currently if I input: "blue, red" then I get all records tagged with blue OR red.
I want to match all records tagged with blue AND red.
Suggestions?
-- EDIT --
My models are like so:
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
A tag has two attributes: ID and Name (string).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该有效:
上面将匹配至少带有红色和蓝色标签的照片。因此,这意味着如果照片具有红色、蓝色和绿色标签,那么该照片也会匹配。
This should work:
Above will match photos that have tags red and blue at least. So that means if a photo has red, blue and green tags, that photo would match too.
您可以将 select 语句更改为以下内容:
这将在 where 子句中正确创建 OR 字符串。
伊恩。
You could change your select statement to the following:
Which will properly create the OR string in the where clause.
ian.
哈哈,这个问题的解决方案不是一个简单的任务——我从 SQL 的角度思考了它,它很丑陋。我想其他人必须尝试过这个,所以我做了一些搜索,发现这篇文章应该对您有帮助:
HABTM 通过“AND”连接查找,而不是“OR”
LOL the solution for this is not a simple task--I thought through it from a SQL standpoint and it was UGLY. I figured somebody else has to have tried this so I did some searching and found this post that should help you:
HABTM finds with "AND" joins, NOT "OR"