2

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.

virtual_monk
  • 120
  • 3
  • 12
  • I think the `LIKE` syntax would be as follows: `LIKE '%?%'` (the `%` being wildcard). – max pleaner Apr 06 '16 at 02:45
  • 1
    This makes no sense. You want an object with `example: "the"` to appear when somebody searches for "thesaurus"? This isn't how `LIKE` works, and you cannot make it work that way. – user229044 Apr 06 '16 at 03:00
  • Yeah, I'm working with legacy code and the associations I need aren't there. I'm going to try to use this search to makeshift a few associations between objects with inconsistent data. Do you have a solution for this? – virtual_monk Apr 06 '16 at 03:07

2 Answers2

2

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)

user229044
  • 232,980
  • 40
  • 330
  • 338
SomeSchmo
  • 665
  • 3
  • 18
  • @arel No, it doesn't: it warns against pure string conditions but this one is escaped with a question mark so it's OK. – snowangel Apr 15 '18 at 15:30
0

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