【问题标题】:Search through sentences搜索句子
【发布时间】:2012-05-06 18:53:04
【问题描述】:

我有一个 Rails 应用程序,并决定进行搜索。我有一个搜索文本字段,控制器会处理所有事情。在我的搜索方法中

def self.search(search)
    if search
      str = []
      search.split.each do |s|
        a = find(:all, :conditions => ['title or content LIKE ?', "%#{s}%" ])
        str = (str + a).uniq
      end

    else
      find(:all)
    end
  end

我希望能够处理多个单词搜索。如果您删除 each...loop,它适用于 1 个单词搜索。 无论如何,我想找到每个被搜索词的相关帖子并返回它们的组合。

例如。如果有人搜索“Greatest Player”,它将返回标题或内容为“Greatest”的所有帖子实例,以及任何标题或内容为“Player”的帖子实例

【问题讨论】:

    标签: ruby-on-rails ruby string search


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      不应该

      a = find(:all, :conditions => ['title or content LIKE ?', "%#{s}%" ])
      

      【讨论】:

      • 或者更好:a = find(:all, :conditions => ['title LIKE ? or content LIKE ?', "%#{s}%", "%#{s}%"])
      • 我打字很快,打错字了,但这不是问题的重点。
      • 如果不是拼写错误,它将表现出您所描述的行为。所以,我只是想帮忙。
      【解决方案3】:

      您只需将 find 语句更改为 Mischa 的代码并添加 return 语句

      工作代码:

      def self.search(search)
          if search
            str = []
            search.split.each do |s|
              a = where(title LIKE ? or content LIKE ?', "%#{s}%", "%#{s}%")
              str = (str + a).uniq
            end
          return str
      
          else
            find(:all)
          end
        end
      

      【讨论】:

      • :all 现在已弃用,我们现在将使用不同的方法。 a = where('title LIKE ? or content LIKE ?', "%#{s}%", "%#{s}%")
      • 也将 LIKE 更改为 ILIKE 以不区分大小写
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 2011-04-09
      • 2016-10-12
      相关资源
      最近更新 更多