如何在Rails搜索中使用LIKE

时间:2018-10-23 04:24:00

标签: ruby-on-rails sql-like

def self.search_by(search_term)

   where("LOWER (course_name) LIKE :search", search_term: "%#{search_term}%")
end

这是我的代码,看来LIKE查询根本不起作用

5 个答案:

答案 0 :(得分:2)

您的代码where("LOWER (course_name) LIKE :search", search_term: "%#{search_term}%")无法正常工作,因为它需要一个参数search,但是您正在传递search_term。因此,将其修改为:

where("LOWER (course_name) LIKE :search", search: "%#{search_term}%") 现在,您将提供期望在"LOWER (course_name) LIKE :search"中使用的变量。

答案 1 :(得分:0)

@venues = Venue.where('name LIKE?',“%#{@ query}%”)

答案 2 :(得分:0)

start = time.time()
def f(m):
    time.sleep(0.5)
    print("yes")
    return 'yes'


def do_stuff(q):
    while True:
        output = q.get()
        final_result = f(output)
        q.task_done()


q = Queue(maxsize=0)
for message_nbr in range(10):
#     q.put(f())
    q.put(message_nbr)

num_threads = 10

for i in range(num_threads):
    worker = Thread(target=do_stuff, args=(q, ))
    worker.setDaemon(True)
    worker.start()

q.join()
print("time: ", time.time() - start)

OR

scope :search_by, -> (search_term){ where("LOWER(course_name) LIKE ?", "%#{search_term.to_downcase}%")}

答案 3 :(得分:0)

将查询更新为

其中(“下级(课程名称)类似: search_term ”, search_term :“%#{ search_term }%”)

用:search_term更改:search关键字,您在查询中使用别名:search,但指定:search_term来分配搜索值。

答案 4 :(得分:0)

可以使用关键字ILIKE代替LIKE来匹配不区分大小写的字符串,因此您不必使用LOWER

此外,您的查询无法正常运行的原因是您必须使用:search_term更改:search别名。

def self.search_by(search_term)
   where("course_name ILIKE :search", search: "%#{search_term}%")
end