好吧,我感觉自己在原地打转。
我有以下 Rails 模型:
class Image < ActiveRecord::Base
has_many :image_tags
has_many :tags, :through => :image_tags
end
class Tag < ActiveRecord::Base
has_many :image_tags
has_many :images, :through => :image_tags
end
class ImageTag < ActiveRecord::Base
belongs_to :image
belongs_to :tag
end
所以基本上我有图像,我有标签,并且图像可以有各种标签。
如果我想找到每张具有一个标签的图像,那很简单,对吧?
def Image.find_by_tag(t)
includes('tags').where(['tags.name = ?', t]).references(:tags)
end
但是我正在绞尽脑汁地试图弄清楚如何同时搜索多个标签(即找到所有标记为“有趣”和“政治”的图像)。
Image.find_by_tag('funny').find_by_tag('political')
始终会出现空集,即使有多个图像同时标记为空集。
非常感谢任何帮助!
最佳答案
尝试使用in
:
def self.by_tags(t)
includes('tags').where('tags.name in(?)', t.map(&:name)).references(:tags)
end
请注意,参数t
必须是一个包含响应name
属性的对象的数组。
关于mysql - 与 Rails 一起迷失 has_many : through multiple search,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21359331/