简体   繁体   English

使用LIKE对未知(动态)查询数进行Rails SQL查询

[英]Rails SQL query on unknown (dynamic) number of queries using LIKE

I have a Rails search form that performs a dynamic query. 我有一个执行动态查询的Rails搜索表单。 That is, the user enters a search like: 也就是说,用户输入类似以下内容的搜索:

(hobby="skiing") OR (gender="male" AND hobby="jogging") 

So, I don't know how many queries I will be searching by until runtime. 因此,在运行时之前,我不知道要搜索多少个查询。

I parse the search query by converting it into a valid SQL query, so the above search would be converted to the following format: 我通过将搜索查询转换为有效的SQL查询来对其进行解析,因此上述搜索将转换为以下格式:

query = "hobby LIKE ? OR (gender LIKE ? AND hobby LIKE ?)"
queries = ["skiing", "male", "jogging"]

For the following query: 对于以下查询:

where(query, queries)

However, the general syntax of the Rails search query is very limiting: 但是,Rails搜索查询的一般语法非常有限:

where(query, query_1, query_2, query_3)

I cannot replace the 'query_n' arguments with an array like I want to, without Rails throwing an error. 我不能用我想要的数组替换'query_n'参数,而Rails不会引发错误。

NoMethodError (undefined method `where' for ["a", "b", "c"]:Array)

Attempting to splat the array yields the same error: 试图图示阵列产生相同的误差:

where(query, *queries)

Again: 再次:

NoMethodError (undefined method `where' for ["a", "b", "c"]:Array)

So what can I do? 那我该怎么办?

EDIT: 编辑:

The full search function looks like this: 完整的搜索功能如下所示:

def self.search(search)
    query = "%#{search}%"
    if search
        includes(:games, :jobs)
        strngs = ["hobby = ? OR name = ? OR gender = ?", "dsfgdsfg", "dsgsdfgsd", "sdfsfsdf"]
        .where(strngs)

What you'll want to do is pass an array as a single argument to where which contains both the query AND the dynamic values. 什么,你会想要做的就是传递一个数组作为一个单一的参数where既包含了查询和动态值。 For example: 例如:

where(["att_1 LIKE ? OR att_2 LIKE ?", "value1", "value2"])

If an array is passed as the first and only argument, then the first element of the array is treated as a template. 如果将数组作为第一个也是唯一的参数传递,则将数组的第一个元素视为模板。 The following array values are treated as the dynamic values for the query template. 以下数组值被视为查询模板的动态值。

For your example, instead of having two separate variables queries and query , combine them into one query variable: 在您的示例中,没有两个单独的变量queriesquery ,而是将它们组合为一个query变量:

# A single array with the query AND values
query = ["hobby LIKE ? OR (gender LIKE ? AND hobby LIKE ?)", "skiing", "male", "jogging"]

# Run the `where` with a single array as the argument
YourModel.where(query)

This will allow you to query the DB with an unknown number of values using LIKE . 这将允许您使用LIKE查询具有未知数量值的数据库。

For reference: Rails where() docs 供参考: Rails where()文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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