简体   繁体   中英

Exact Term Search In Rails

I'm trying to build a basic search where only the entire exact search term shows results. Currently it is showing results based on individual words.

Here's the code from the model:

def search
  find(:all, :conditions => ['term' == "%#{search}%"])
end

Sorry in advance. I'm very new to rails!

Thank you.

Remove the % from "%#{search}%" so it's "#{search}" .

% is a wildcard that matches every result containing the word. So "%tea%" for example would match tear, nestea, and steam, when that's not what you want.

This should yield an exact match:

def search find(:all, :conditions => ['term' == "#{search}"]) end

Your code doesn't work for several reasons.

  1. You do not pass any value to that method. Therefore search will always be nil .
  2. The ['term' == "%#{search}%"] condition doesn't make much sense because - as I said before - search is undefined and therefore the condition will is the same as ['term' == "%%"] . The string term is not equal to %% therefore the whole condition is basically: [false] .
  3. Rails 5.0 uses a different syntax for queries. The syntax you used is very old and doesn't work anymore.

I would do something like this:

# in your model
scope :search, -> (q) { 
  q.present? ? where("column_name LIKE :query", query: "%#{q}%") :none 
}

# in your controller
def set_index 
  @b = Best.search(params[:search]).order(:cached_weighted_score => :desc)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM