问题
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