【问题标题】:Rails: Search all images that are tagged with a certain tagRails:搜索所有带有特定标签的图像
【发布时间】:2012-08-29 00:47:10
【问题描述】:

我有 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

现在我已经添加了一些带有相应(预定义)标签的图像,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"}

执行这种图像搜索的最佳方法是什么?

【问题讨论】:

  • 我认为这很好,一件事是出于安全原因将其设为“发布”方法。而且您只需在 Tag 模型下编写范围即可获取与标签相关的所有项目。

标签: ruby-on-rails ruby-on-rails-3 search tags


【解决方案1】:

我认为这应该可行:

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

【讨论】:

  • @shioyama :在这种情况下,我们将根据 tag_id 2 或 tag_id 3 获取所有图像,但是如果我只想要那些由两个标签都标记的图像,那将是什么代码其中之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多