简体   繁体   中英

Sorting Search Results by multiple factors

Using RoR 3.9, I have a search that searches for comma separated keywords; for example "apple, orange" will find any record that has the word "apple" or the word "orange". I would like to be able to sort the results so that any records that contain both words are displayed first. For example

A search for "Apple, Orange" would display the record

"Orange slices and apple pie"

before the record

"Apple Juice"

even if Apple Juice is found first. How can I add this first level sort before sorting by alphanumeric order? I'm thinking I could do this in the controller index action by setting the order of the index search to first display any records that have "apple" AND "orange", then display all other records that have "apple" OR "orange", I just don't know how to do such a thing.

Here is the scope that searches for a set of comma separated values:

    scope :by_description, ->(desc=nil) {
    if desc.blank?
      all
    else
      terms = desc.split(/\s*,\s*/).map { |t| t.strip }.map { |t| "%#{t}%" }
      where( ( ["#{table_name}.description like ?"] * terms.count).join(' or '), *terms )
    end
    }

I call the scope in my controller like so:

def index

@drawings = Drawing.by_description(params[:drawings][:description]).all
...

You could use sort by and a lambda to compare the results:

description = params[:drawings][:description].to_s
@drawings.sort_by { |d| d.description.index( description ) }

This will find the position of the substring in your description. The lowest index will mean the substring shows up earliest in the description.

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