在单个搜索文本字段 (RAILS) 中搜索多个关键字 [英] Search on multiple keywords in a single search text field (RAILS)

查看:52
本文介绍了在单个搜索文本字段 (RAILS) 中搜索多个关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是个新手,正在尝试在 Rails 中搜索数据库.我有一个模型和数据库,在 'name' 属性下有一个名称列表.我希望能够在单个搜索字段中输入搜索关键字,该输入可以是一个词或两个词或更多,具体取决于用户想要的结果的具体程度.

I'm fairly new and playing around with searching databases in Rails. I have a model and database that has a list of names under the 'name' attribute. I want to be able to enter search keywords into a single search field and this input can be one word or two words or more, depending on how specific a result the user wants.

现在,我正在使用如下所示的难看的东西,它最多可以执行 3 个搜索词.有没有办法使search_length"关键字动态化?find 方法显然是重复的,但我不确定如何使其自动化,也没有在网上其他地方找到任何有用的建议.

Right now, I'm using something ugly as shown below, which will do a maximum of 3 search terms. Is there a way to make this dynamic for 'search_length' keywords? The find method is clearly repetitive, but I'm not sure how to automate it and haven't found any useful suggestions elsewhere online.

def self.search(search)

  if search
    search_length = search.split.length
    find(:all, :conditions => ['name LIKE ? AND name LIKE ? AND name LIKE ?', 
    "%#{search.split[0]}%", "%#{search.split[1]}%", 
    "%#{search.split[search_length1]}%"])
  else
    find(:all)
  end
end

除此之外,到目前为止都喜欢 Rails.

Other than this, loving Rails so far.

非常感谢,列夫

推荐答案

来自 Łukasz Śliwa 的代码如果您用另一个 % 符号关闭 name 变量,效果会很好.

The code from Łukasz Śliwa works great if you close the name variable with the other % sign.

上面的完整代码对我有用.很棒的帖子.

The complete code from above working for me. Great post.

def self.search(search)

  if search
    search_length = search.split.length
    find(:all, :conditions => [(['name LIKE ?'] * search_length).join(' AND ')] + search.split.map { |name| "%#{name}%" })
  else
    find(:all)
  end

end

这篇关于在单个搜索文本字段 (RAILS) 中搜索多个关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆