简体   繁体   中英

Seach two columns together in a single search column

I am using filterrifc gem in my rails app for adding filters to the index list.I have a users table with firstname, lastname and middlename as the field. What I am trying to do is search through all these column in a single search column. The issue I am facing is: When I am search for Jimmy then I get a list of all Jimmys in firstname, lastname and middlename. But When I try search for specific Jimmy Wilson it doesnt work. It still just shows Jimmys not the specific Jimmy Wilson . Please help me find the issue.

user.rb

scope :search_name, lambda { |query|
    return nil  if query.blank?

    terms = query.downcase.split(/\s+/)

    terms = terms.map { |e|
      ('%' + e + '%').gsub(/%+/, '%')
    }

    num_or_conds = 3
    where(
      terms.map { |term|
        "(LOWER(users.lastname) LIKE ?) OR (LOWER(users.firstname) LIKE ?) OR (LOWER(users.middlename) LIKE ?)"
      }.join(' AND '),
      *terms.map { |e| [e] * num_or_conds }.flatten
    )
  } 

AND has higher precedence than OR therefore you have to change where you add parentheses:

where(
  terms.map { |term|
    "(LOWER(users.lastname) LIKE ? OR LOWER(users.firstname) LIKE ? OR LOWER(users.middlename) LIKE ?)"
  }.join(' AND '),
  *terms.map { |e| [e] * num_or_conds }.flatten
)

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