ActiveRecord Fuzzy Search

独自空忆成欢 提交于 2020-01-04 09:11:53

问题


I'm looking to perform a search to find an object similar to this:

Object(id: 1, example: "abc")

by using a search like this:

params[:search] = "abcdef"
Object.where("example LIKE ?", "#{params[:search]%")

but am only able to use the above example if my search has less characters than my object, not more.


回答1:


I think it should be

params[:search] = "abcdef"
Object.where("example LIKE ?", "%#{params[:search]}%")

Also might want to use ilike for case insensitive search (if you're using postgres)




回答2:


Note: the fuzzily gem does not work with Rails 6. This solution has been deprecated.

The fuzzily gem allows you to do fuzzy searching of ActiveRecord models that you've instrumented appropriately.

Fuzzily finds misspelled, prefix, or partial needles in a haystack of strings. It's a fast, trigram-based, database-backed fuzzy string search/match engine for Rails.

Once you've installed the gem, you can instrument your model as follows:

class MyStuff < ActiveRecord::Base
  # assuming my_stuffs has a 'name' attribute
  fuzzily_searchable :name
end

You can then perform fuzzy searches as follows:

MyStuff.find_by_fuzzy_name('Some Name', :limit => 10)
# => records


来源:https://stackoverflow.com/questions/36440513/activerecord-fuzzy-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!