在将数据添加到数组之前检查Tag是否存在

时间:2010-10-15 17:18:08

标签: ruby-on-rails

我有以下代码:

unless params[:search_tags].nil?
  logger.debug "Going through tags now #{params[:search_tags]}"
  params[:search_tags].split(",").each{ |tag|
    tag.strip!
    tag = '%' + tag + '%'
    tags = Tag.find(:all, :conditions => ["name LIKE ?", tag])
    if tags.nil? || tags.empty? # I'm searching for something that does not actually exist!
      @listings = []
    else  
      tags.each {|tag|
        logger.debug "Checking #{tag}"; @listings = @listings & tag.listings
      }
    end
  }  
  logger.debug "I have #{@listings.size} listings left after hashtag stripping"
end

问题是,如果我输入2个标签而1不存在则不返回任何结果。我想在添加标签之前添加一个检查标签是否存在。

1 个答案:

答案 0 :(得分:0)

试试这个:

   unless params[:search_tags].nil?
      logger.debug "Going through tags now #{params[:search_tags]}"
      params[:search_tags].split(",").each do |tag|
        tag.strip!
        tag = '%' + tag + '%'
        tags = Tag.find(:all, :conditions => ["name LIKE ?", tag])

        @listings = []

        unless tags.nil || tags.empty?  
          tags.each do |tag|
            logger.debug "Checking #{tag}"; 
            @listings << tag.listings
          end
        end
        @listings = @listings.uniq
      end  
      logger.debug "I have #{@listings.size} listings left after hashtag stripping"
    end