1

私は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)タグを持ついくつかの画像を追加しました。画像/新規の関連コードは次のとおりです。

%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

特定のタグが付いているすべての画像を検索するにはどうすればよいですか?1つ以上の事前定義されたタグでタグ付けされたすべての画像を表示するには@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"}

この種の画像検索を実行するための最良の方法は何ですか?

4

1 に答える 1

4

私はこれがうまくいくと思います:

images = Image.includes(:tags).where('tags.id' => params['tag_ids']).all
于 2012-09-04T12:52:06.010 に答える