我有3个型号:
class Image < ActiveRecord::Base
attr_accessible :name, :size, :image
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
end
class Tag < ActiveRecord::Base
attr_accessible :name
has_many :taggings, :dependent => :destroy
has_many :images, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :image
belongs_to :tag
attr_accessible :image_id, :tag_id
end
现在我添加了一些带有相应(prefedined)标签的图像,images / new的相关代码是:
%div.field
= f.label "Tag"
%br/
- for tag in Tag.all
= check_box_tag "image[tag_ids][]", tag.id, @image.tags.include?(tag)
= tag.name
我现在如何搜索所有具有特定标签的图像?我需要一个@images来显示所有用一个或多个预定义标签标记的图像。我在复选框的帮助下选择了这些标签:
%h1
Search an image
%p
= form_tag '/tagsearch', :method => 'get' do
- for tag in Tag.all
= check_box_tag 'tag_ids[]', tag.id
= tag.name
= submit_tag "Search Images"
因此,此搜索的参数现在是(例如,使用tag_ids 2和3搜索所有图像):
{"utf8"=>"✓",
"tag_ids"=>["2",
"3"],
"commit"=>"Search Images"}
执行此类图像搜索的最佳方法是什么?
答案 0 :(得分:4)
我认为这应该有效:
images = Image.includes(:tags).where('tags.id' => params['tag_ids']).all