Reputation: 817
I have 3 models:
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
Now I have added a few images with corrisponding (prefedined) tags, the relevant code for images/new is:
%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
How can I now search all images that have a certain tag? I need an @images to display all images that are tagged with one or more predefined tags. I choose these tags with help of checkboxes:
%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"
So, the params of this search are now (e.g. a search for all images with the tag_ids 2 and 3):
{"utf8"=>"✓",
"tag_ids"=>["2",
"3"],
"commit"=>"Search Images"}
What is the best way to perform this kind of image search?
Upvotes: 1
Views: 1023
Reputation: 27374
I think this should work:
images = Image.includes(:tags).where('tags.id' => params['tag_ids']).all
Upvotes: 4