我目前的数据库结构是我有许多标签的地方。我希望能够搜索包含用户输入搜索框的所有标记的位置。我当前的代码看起来像这样,它只会找到至少有一个指定标签的地方:
tags = params[:tags]
Place.find(:all, :include => [:tags], :conditions => ['tags.title IN (?)', tags])
答案 0 :(得分:1)
试试这个:
tags = params[:tags]
Place.find(:all, :include => [:tags], :conditions => ['places.id IN
(SELECT place_id FROM
(SELECT place_id, count(place_id) AS tags_count FROM places_tags WHERE tag_id IN
(SELECT id FROM tags WHERE title IN (?))
GROUP BY place_id) AS count_table
WHERE tags_count = ?)', tags, tags.size])
说明:首先找到数组中的所有标签,然后计算每个地方找到的次数(相当于匹配了多少个标签),然后只选出所有标签匹配的地方。
答案 1 :(得分:0)
如果你使用的是标签和Ruby on Rails,我强烈推荐acts_as_taggable_on。
这可以让你做到这样的事情:
class User < ActiveRecord::Base
# Alias for <tt>acts_as_taggable_on :tags</tt>:
acts_as_taggable
acts_as_taggable_on :skills, :interests
end
@user = User.new(:name => "Bobby")
@user.tag_list = "awesome, slick, hefty" # this should be familiar
@user.skill_list = "joking, clowning, boxing" # but you can do it for any context!
@user.skill_list # => ["joking","clowning","boxing"] as TagList
@user.save
@user.tags # => [<Tag name:"awesome">,<Tag name:"slick">,<Tag name:"hefty">]
@user.skills # => [<Tag name:"joking">,<Tag name:"clowning">,<Tag name:"boxing">]
@frankie = User.create(:name => "Frankie", :skill_list => "joking, flying, eating")
User.skill_counts # => [<Tag name="joking" count=2>,<Tag name="clowning" count=1>...]
@frankie.skill_counts
非常容易实施。而且您不必担心如何在数组中查找特定元素。