And*_*rew 1 sql activerecord ruby-on-rails ruby-on-rails-3
我的ActiveRecord模型中有以下查询方法:
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
select('distinct photos.*').joins(:tags).where('tags.name' => array )
end
Run Code Online (Sandbox Code Playgroud)
因此,这将查找所有记录,这些记录具有从逗号分隔列表中获取的标记并转换为数组.
目前,这会将记录与任何匹配的标记匹配 - 如何使其在匹配所有标记的位置工作.
IE:如果我现在输入:"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
Run Code Online (Sandbox Code Playgroud)
标签有两个属性: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
Run Code Online (Sandbox Code Playgroud)
上面将匹配至少有红色和蓝色标签的照片.这意味着如果照片有红色,蓝色和绿色标签,那么这张照片也会匹配.
| 归档时间: |
|
| 查看次数: |
1480 次 |
| 最近记录: |