user929062
user929062

Reputation: 817

Rails: Search all images that are tagged with a certain tag

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

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

I think this should work:

images = Image.includes(:tags).where('tags.id' => params['tag_ids']).all

Upvotes: 4

Related Questions