开发者

check if Tag exists before adding it to array

开发者 https://www.devze.com 2023-01-20 07:42 出处:网络
I have the following code: 开发者_如何学Gounless params[:search_tags].nil? logger.debug \"Going through tags now #{params[:search_tags]}\"

I have the following code:

开发者_如何学Gounless 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

Problem is, if I enter 2 tags and 1 does not exist it returns no results. I'd like to add a check check if a tag exists before it is added.


Try this:

   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
0

精彩评论

暂无评论...
验证码 换一张
取 消