简体   繁体   中英

How to include a LIKE clause in Rails query on HABTM join table

I have 2 models - Candidate and Keyword and has_and_belongs_to_many association between them.

If i want to find all candidates where a keyword.name equals to sth - i just need to do a search in Candidate model like this-and it works fine.

def self.search(search)
        includes(:keywords).where("keywords.name" => "#{search}")
end

But what if i need to search for candidates where keyword.name contains a string (equivalent of "LIKE" clause)? I've tried multiple ideas but cannot find a good solution...

Try this:

.where("keywords.name LIKE ?", "%#{search}%")

EDIT

Note: this requires using .joins instead of .includes before the WHERE query.

You can use a LIKE query using the parameter replacement syntax, with any SQL dialect supported by RAILS:

def self.search(search)
  includes(:keywords).where("keywords.name LIKE ?", "%#{search}%")
end

This will replace the '?' in the query string with the amended search value to produce this SQL condition with a search string of "sth":

WHERE keywords.name LIKE '%sth%'  

The search value is bookended with "%" (SQL wildcard character) outside the query string. Including the "%" inside the query string will cause them to appear outside the quoted representation of the search value:

WHERE keywords.name LIKE %'sth'%  

which will simply not work.

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